Java Regex Tokenizing

时间:2017-07-24 17:58:01

标签: java regex token delimiter

这里是regex的新手哈哈。

我们说我有一个字符串:

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 没有分开,因为我们没有做组(i)?为什么要打印\ newline?

1 个答案:

答案 0 :(得分:2)

您可以在Java中使用此正则表达式:

(?m)^([^=]+)=(.+)\R+^(#.*)

RegEx Demo

RegEx分手:

  • (?m):启用MULTILINE模式
  • ^([^=]+)=:匹配到=并在第1组中捕获,然后是=
  • (.+):匹配第2组
  • 中的其余部分
  • \R+:匹配1 +换行符
  • ^(#.*):匹配以#3
  • 组中的#开头的整行