[英]How to split this string using Java Regular Expressions
I want to split the string 我想分割字符串
String fields = "name[Employee Name], employeeno[Employee No], dob[Date of Birth], joindate[Date of Joining]";
to 至
name
employeeno
dob
joindate
I wrote the following java code for this but it is printing only name other matches are not printing. 我为此编写了以下Java代码,但它仅打印其他匹配项不打印的名称。
String fields = "name[Employee Name], employeeno[Employee No], dob[Date of Birth], joindate[Date of Joining]";
Pattern pattern = Pattern.compile("\\[.+\\]+?,?\\s*" );
String[] split = pattern.split(fields);
for (String string : split) {
System.out.println(string);
}
What am I doing wrong here? 我在这里做错了什么?
Thank you 谢谢
This part: 这部分:
\\[.+\\]
matches the first [
, the .+
then gobbles up the entire string (if no line breaks are in the string) and then the \\\\]
will match the last ]
. 匹配第一个
[
, .+
然后吞噬整个字符串(如果字符串中没有换行符),然后\\\\]
将匹配最后一个]
。
You need to make the .+
reluctant by placing a ?
你需要做的
.+
通过放置一个不情愿?
after it: 之后:
Pattern pattern = Pattern.compile("\\[.+?\\]+?,?\\s*");
And shouldn't \\\\]+?
而且不是
\\\\]+?
just be \\\\]
? 只是
\\\\]
吗?
在http://gskinner.com/RegExr/?2sa45上有一个在线正则表达式测试器,当您尝试了解正则表达式以及如何将其应用于给定输入时,它将为您提供很多帮助。
WOuld it be better to use Negated Character Classes to match the square brackets? 使用否定字符类来匹配方括号会更好吗? \\[(\\w+\\s)+\\w+[^\\]]\\]
\\ [((ww + \\ s)+ \\ w + [^ \\]] \\]
You could also see a good example how does using a negated character class work internally (without backtracking)? 您还会看到一个很好的示例,使用否定的字符类在内部如何工作(不回溯)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.