简体   繁体   English

Java:替换字符串(用方括号!)

[英]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) 读取Excel文档(.xlsx,使用SmartXLS),并将内容保存在长字符串(每个单元格都换一行)中
  • 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 根据配置文件中的示例,读取配置文件,然后转换长字符串(replaceAll)中的子字符串和/或添加前缀
  • Outputs the final String into a txt file 将最终的字符串输出到txt文件中

Example for the conversion: abc (with a tab in between each of the parts), eg "its[ ]bracket" -> "itsabracket" with 转换示例:abc(每个部分之间都有一个制表符),例如“ its [] bracket”->“ itsabracket”

tagname [ ] a

in the config file ("[ ]" gets replaced with "a"). 在配置文件中(“ []”被替换为“ 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. a是告诉我要转换哪些列的标签,b是原始子字符串,c是必须转换为String的字符串。

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"): for“ []”->“ a”将[a]写入输出文件,如果我先执行以下操作,则当它读取配置文件并将所有内容保存在“ convert”数组中时,它将引发PatternSyntaxException(“ Unclosed character靠近索引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. 它再次输出“ [a]”。

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. Use String.replace它接受与replaceAll不同的字符序列。您不必对[]等使用转义字符。

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

input 输入
its[][]]bracket 其[] []]托架
tagname [ ] a 标记名[] a

output 产量

itsaa]bracket itsaa]托架

Hope this is what you want to achieve using your code. 希望这是您希望使用代码实现的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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