简体   繁体   中英

Java: Replace String (with brackets!)

I'm currently working on a small program that:

  • Reads an Excel document (.xlsx, using SmartXLS) and saves the content in a long String (a new line for each cell)
  • Reads a config file and then converts substrings in the long String (replaceAll) and/or adds a prefix, according to the examples in the config file
  • Outputs the final String into a txt file

Example for the conversion: abc (with a tab in between each of the parts), eg "its[ ]bracket" -> "itsabracket" with

tagname [ ] a

in the config file ("[ ]" gets replaced with "a"). a is the tag that tells me, what columns get converted, b is the original substring and c is the String b has to be converted into.

The problem is: I already know that brackets (round, curly and square) are going to be used in the config file but I don't know, if it's going to be just a single one or maybe even longer phrases (with letters, digits,..) in between the brackets.

String s = s.replaceAll(convert[i].original, convert[i].new);

for "[ ]" -> "a" writes [a] into the output file and if I do the following first, when it's reading the config file and saves everything in the "convert" array, it throws a PatternSyntaxException ("Unclosed character class near index 0"):

if(ss.contains("[")) {
    ss = ss.replaceAll("[", "\\[");
} else if(ss.contains("]")) {
    ss = s.replaceAll("]", "\\]");
}

With

if(ss.contains("\\[")) {
    ss = ss.replaceAll("\\[", "\\\\[");
} else if(ss.contains("\\]")) {
    ss = s.replaceAll("\\]", "\\\\]");
}

it outputs "[a]" again.

Any ideas, how I can make this work?

Use String.replace It accepts character sequence unlike replaceAll.You dont have to use escape characters for [] etc.

 String s = s.replace(convert[i].original, convert[i].new);

input
its[][]]bracket
tagname [ ] a

output

itsaa]bracket

Hope this is what you want to achieve using your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM