Java - 使用多个分隔符时的字符串解析或 split() 错误
好吧,你可能会说这是重复的帖子,但它是不同的。
我正在开发一个程序,该程序正在处理用户指定的某种删除分隔符。如果分隔符只是一个字符(特殊或非特殊),我的程序就可以工作。但是,如果用户输入是字符串,则会从消息字符串中删除分隔符的所有字符。
前任。字符串消息 = "ab\nc[d]e{fMardk1g(h)i}j"; 输出将是:bcefghij 但预期的输出是 abcdefghij
我是使用 Pattern 类的新手,所以我不知道问题出在哪里。
这是有问题的代码(我将其放在测试类中,以便隔离问题)
:
public class ParsingTest {
public static void main(String[] args) {
String[] delimiters = { "Mardk1", "\n", "[", "]", "{", "}", "(", ")" };
StringBuilder regexp = new StringBuilder("");
regexp.append("[");
for(String s : delimiters) {
regexp.append("[");
regexp.append(Pattern.quote(s));
regexp.append("]");
}
regexp.append("]");
String message = "ab\nc[d]e{fMardk1g(h)i}j";
StringBuilder result = new StringBuilder("");
String[] a = message.split(regexp.toString());
for(String string : a) {
result.append(string);
}
System.out.println(result);
for(String str: a) System.out.print(str);
System.out.println();
}
}
Ok, you might say that this is a duplicate post but it is different.
I am working on a program that is working on some kind of deleting delimiters specified by the user. My program is working if the delimiter is only a single character (special or not). However, if the user input is a string, it removes the all characters of the delimiter from the message string.
ex. String message = "ab\nc[d]e{fMardk1g(h)i}j";
output will be : bcefghij
but the expected output is abcdefghij
I'm new in using the Pattern class, so I don't know where the problem lies.
Here's the code in question (I put it in a testing class so I can isolate the problem):
import java.util.regex.Pattern;
public class ParsingTest {
public static void main(String[] args) {
String[] delimiters = { "Mardk1", "\n", "[", "]", "{", "}", "(", ")" };
StringBuilder regexp = new StringBuilder("");
regexp.append("[");
for(String s : delimiters) {
regexp.append("[");
regexp.append(Pattern.quote(s));
regexp.append("]");
}
regexp.append("]");
String message = "ab\nc[d]e{fMardk1g(h)i}j";
StringBuilder result = new StringBuilder("");
String[] a = message.split(regexp.toString());
for(String string : a) {
result.append(string);
}
System.out.println(result);
for(String str: a) System.out.print(str);
System.out.println();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用了错误的分组结构。您正在构建一个像 [xyz] 这样的模式,它将匹配任何单个字符 x、y 或 z。您想要匹配多个完整字符串中的任何一个,因此需要正常的
()
样式分组和交替运算符 (|
)。有关更多详细信息,请参阅Pattern
文档。尝试这个来构建正则表达式:
You're using the wrong kind of grouping construct. You're building a pattern like [xyz] which will match any single character x, y or z. You want to match any of several full strings, so you want the normal
()
style grouping, and the alternation operator (|
). Have a look at thePattern
documentation for more details.Try this instead to build up the regex: