Java如何使用模式匹配器使用正则表达式来查找某些字符串

时间:2014-03-10 13:19:53

标签: java regex matcher

我不熟悉模式&匹配器,我很困惑这个问题。

我有一个字符串,我想在Java中操作。 我明白我必须使用

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(in);

while(m.find()) {
     String found = m.group(1).toString();
}

但在我的字符串中,假设我有以下示例:

String in = "test anything goes here [A#1234|567]"; //OR
String in = "test anything goes here [B#1234|567]"; //OR
String in = "test anything goes here [C#1234|567]";

我想在字符串中找到[A# | ][B# | ][C# | ],如何使用正则表达式查找表达式?

4 个答案:

答案 0 :(得分:1)

在正则表达式中使用[ABC]#来匹配您的表达式。

Pattern p = Pattern.compile("(\\[[ABC]#.*?\\])");

如果字段为数字,则可以安全地使用\d+

Pattern p = Pattern.compile("(\\[[ABC]#\\d+\\|\\d+\\])");

答案 1 :(得分:1)

我使用简单的Pattern,如下例所示:

String[] in = { "test anything goes here [A#1234|567]",
            "test anything goes here [B#1234|567]",
            "test anything goes here [C#1234|567]" };

    Pattern p = Pattern.compile("\\[[A-Z]#\\d+\\|\\d+\\]");
    for (String s: in) {
        Matcher m = p.matcher(s);
        while (m.find()) {
            System.out.println("Found: " + m.group());
        }
    }
}

<强>输出

Found: [A#1234|567]
Found: [B#1234|567]
Found: [C#1234|567]

我假设您的Pattern有特定限制:

  • [
  • 开头
  • 后跟一个大写非重音字母
  • 后跟#
  • 后跟任意位数
  • 后跟|
  • 后跟任意位数
  • 后跟]

答案 2 :(得分:0)

尝试:

Pattern p = Pattern.compile("(\\[[A-Z]#.*\\])");

如果你想匹配任何大写的A到Z.不清楚你是否想要[]之间的所有数据。

答案 3 :(得分:0)

我的解决方案:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Some {
    public static void main(String[] args) throws java.lang.Exception {
        String[] in = {
            "test anything goes here [A#1234|567]",
                "test anything goes here [B#1234|567]",
                "test anything goes here [C#1234|567]"
        };

        Pattern p = Pattern.compile("\\[(.*?)\\]");
        for (String s: in ) {
            Matcher m = p.matcher(s);
            while (m.find()) {
                System.out.println("Found: " + m.group().replaceAll("\\d", ""));
            }
        }

    }
}

这使用您的原始正则表达式。

演示: http://ideone.com/4Z5oYD

相关问题