Reputation: 409
How to reverse string based on non alphabetic delimiters? I suspect my regex may be the problem.
String fileContent = "Joe'); MAKE TEST random;--";
String[] splitWords = fileContent.split("[^a-zA-Z0-9']+");
StringBuilder stringBuilder = new StringBuilder();
for (String word : splitWords) {
int idx = fileContent.indexOf(word, stringBuilder.length());
String delim = fileContent.substring(stringBuilder.length(), idx);
stringBuilder.append(delim);
StringBuilder output = new StringBuilder(word).reverse();
stringBuilder.append(output);
}
return stringBuilder.toString();
Current output: 'eoJ); EKAM TSET modnar
Desired output: eoJ'); EKAM TSET modnar;--
Upvotes: 0
Views: 97
Reputation: 14238
You don't need a regex for this. It seems you want to reverse characters that are only alphabets or digits. Then you could do this way - get the start and end indices of the character array where you find the character to be a letter or digit and then reverse in place. Then return a new String with the characters reversed in place.
private static void reverseWords(char[] c) {
int start = 0, end = c.length;
while ( start < end ) {
int pre = start;
while ( start < c.length && Character.isLetterOrDigit(c[start]) )
start++;
if ( pre < start )
reverseWord(c, pre, start-1);
start++;
}
}
private static void reverseWord(char[] c, int start, int end) {
while ( start < end ) {
char temp = c[start];
c[start] = c[end];
c[end] = temp;
start++;
end--;
}
}
You can test this code here
Upvotes: 2
Reputation: 269
Your code works with two changes:
String fileContent = "Joe'); MAKE TEST random;--"; String[] splitWords = fileContent.split("\W"); // W is non word character or I forgot
StringBuilder stringBuilder = new StringBuilder();
for (String word : splitWords) {
int idx = fileContent.indexOf(word, stringBuilder.length());
String delim = fileContent.substring(stringBuilder.length(), idx);
stringBuilder.append(delim);
StringBuilder output = new StringBuilder(word).reverse();
stringBuilder.append(output);
}
// did we have trailing delimiter ?
if(fileContent.length()!=stringBuilder.length())
{ //append remaining
stringBuilder.append(fileContent.substring(stringBuilder.length()));
}
return stringBuilder.toString();
Upvotes: 1
Reputation: 627056
You may match and reverse only chunks of 1+ letters (with a simple \p{L}+
pattern) and keep the rest as is:
String s = "Joe'); MAKE TEST random;--";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("\\p{L}+").matcher(s);
while (m.find()) {
String replacement = new StringBuilder(m.group()).reverse().toString();
m.appendReplacement(result, replacement);
}
m.appendTail(result);
System.out.println(result.toString()); // => eoJ'); EKAM TSET modnar;--
See the Java demo online.
Upvotes: 1