【发布时间】:2017-07-24 17:58:00
【问题描述】:
这里是正则表达式的新手哈哈。
假设我有一个字符串:
String toMatch = "TargetCompID=NFSC_AMD_Q\n" +
"\n## Bin's verifix details";
在 .cfg 文件中显示为:
TargetCompID=NFSC_AMD_Q
## Bin's verifix details
我想将它标记为一个数组:
{"TargetCompID", "NFSC_AMD_Q", "## Bin's verifix details"}
当前代码,但没有任何输出:
static void regexTest(String regex, String toMatch) {
Pattern patternTest = Pattern.compile(regex);
Matcher matcherTest = patternTest.matcher(toMatch);
while (matcherTest.find()) {
for (int i = 1; i <= matcherTest.groupCount(); i++) {
System.out.println(matcherTest.group(i));
}
}
}
public static void main(String[] args) throws Exception {
String regex = "^[^=]+.*$" + "|" + "^#+.*$";
String toMatch = "TargetCompID=NFSC_AMD_Q\n" +
"\n" +
"## Bin's verifix details";
String testRegex = ".*";
String testToMatch = " ### Bin";
regexTest(regex1, toMatch);
System.out.println("----------------------------");
// regexTest(testRegex, testToMatch);
编辑
while (matcherTest.find()) {
for (int i = 1; i < matcherTest.groupCount(); i++) {
System.out.println(matcherTest.group(i));
}
打印:
TargetCompID
NFSC_AMD_Q
但不是
## Bin's verifix details
为什么?
还有这段代码:
while (matcherTest.find()) {
System.out.println(matcherTest.group());
}
只打印
TargetCompID=NFSC_AMD_Q
## Bin's verifix details
TargetCompID 和 NSFC_AMD_Q 是不是因为我们不做 group(i) 而没有分开?为什么要打印\换行符?
【问题讨论】:
-
为什么人们投反对票?我很困惑。经过几个小时的研究,我并不是没有尝试自己解决它。请评论您投反对票的原因。
-
我不懂投反对票,你展示了你的尝试。
-
但是,不要通过包含我建议的解决方案和更改您问题的性质来编辑您的问题。您可以在我的答案下方留下评论,我会解决它们。例如:
for (int i = 1; i < matcherTest.groupCount(); i++)应该是:for (int i = 1; i <= matcherTest.groupCount(); i++) -
现在工作!谢谢 :) 我会尝试将其恢复为旧版本。
-
最后一件事,
while(matcherTest.find) {System.out.println(matcherTest.group()); }为什么要打印新行/空行?
标签: java regex token delimiter