谁能帮我在哪里做错了?
我的示例文字:
{[|Name:A|Class:1|Sex:Male|][|Name:B|Class:2|Sex:Female|][|Name:C|Class:3|Sex:Male|]}
预期产量:
|Name:A|Class:1|Sex:Male|
Name:A
Class:1
Sex:Male
|Name:B|Class:2|Sex:Female|
Name:B
Class:2
Sex:Female
|Name:C|Class:3|Sex:Male|
Name:C
Class:3
Sex:Male
电流输出
|Name:A|Class:1|Sex:Male|
Name:A
Sex:Male
|Name:B|Class:2|Sex:Female|
Name:B
Sex:Female
|Name:C|Class:3|Sex:Male|
Name:C
Sex:Male
我的程序:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex {
public static void main(String[] args) {
String example = "{[|Name:A|Class:1|Sex:Male|][|Name:B|Class:2|Sex:Female|][|Name:C|Class:3|Sex:Male|]}";
Pattern curlyBraces = Pattern.compile("\\[(.*?)\\]");
Matcher m = curlyBraces.matcher(example);
while (m.find()) {
System.out.println(m.group(1));
String element = m.group(1);
Pattern pipe = Pattern.compile("\\|(.*?)\\|");
Matcher mPipe = pipe.matcher(element);
while (mPipe.find()) {
System.out.println(mPipe.group(1));
}
}
}
}
最佳答案
您的问题是"\\|(.*?)\\|"
仅在行中匹配|Name:A|
和|Sex:Male|
|Name:A|Class:1|Sex:Male|
因为正则表达式会消耗它匹配的字符,因此
|
和Name:A
之间的Class:1
只能匹配一次。使用lookaround assertions来解决该问题-他们不使用匹配的文本:
Pattern pipe = Pattern.compile("(?<=\\|).*?(?=\\|)");
Matcher mPipe = pipe.matcher(element);
while (mPipe.find()) {
System.out.println(mPipe.group(0));
}
如果您不希望为空值,则另一种可能性是匹配所有“非管道”字符:
Pattern pipe = Pattern.compile("[^|]+");
Matcher mPipe = pipe.matcher(element);
while (mPipe.find()) {
System.out.println(mPipe.group(0));
}
关于java - Java Regex调整,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35194704/