Java:如何根据非字母定界符反转字符串?

如何基于非字母定界符反转字符串?我怀疑我的正则表达式可能是问题。

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;--

评论
  • 小妖小姐
    小妖小姐 回复

    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.