繁体   English   中英

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

[英]Java how to use pattern matcher using regular expressions to find certain string

我对模式和匹配器不熟悉,因此我对这个问题深感困惑。

我有一个要在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# | ] [A# | ][B# | ] [B# | ][C# | ] [C# | ]在字符串中,如何使用正则表达式查找表达式?

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

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

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

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

我将在以下示例中使用一个简单的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有特定的限制:

  • [
  • 后跟一个大写的非重音字母
  • 跟着#
  • 后跟任意数量的数字
  • 依次为|
  • 后跟任意数量的数字
  • 其次是]

尝试:

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

如果要匹配任何大写字母A到Z。但是不清楚是否需要[]之间的所有数据。

我的解决方案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM