繁体   English   中英

Matcher类Java-在同一行上匹配多个子字符串

[英]Matcher Class Java - Matching Multiple Sub-strings on Same Line

我正在研究一个类,其目的是查找一行文本,并查找包含某些特定字符(在本例中为字符“ ABC123”)的所有字符串或子字符串。

我已经编写的当前代码部分起作用,但是只能在一行文本中找到第一个子字符串...换句话说,如果正在查看的文本行包含多个包含“ ABC123”的子字符串,它仅查找并返回第一个子字符串。

如何修改代码,以便在文本行中找到所有子字符串?

在我当前的代码下面:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
//For grabbing the Sub-string and separating it with white space


public class GrabBLSubString {
    public static void main(String[] args) {
        test("Viuhaskfdksjfkds  ABC1234975723434 fkdsjkfjaksjfklsdakldjsen ABC123xyxyxyxyxyxyxyxyxyx");
        test("ABC1234975723434");
        test("Viuhaskfdksjfkds  APLIC4975723434 fkdsjkfjaksjfklsdakldjsen");
        test("abc ABC12349-75(723)4$34 xyz");
    }
    private static void test(String text) {
        Matcher m = Pattern.compile("\\bABC123.*?\\b").matcher(text);//"\\bABC123.*?\\b"____Word boundary // (?<=^|\s)ABC123\S*__For White spaces
        if (m.find()) {
            System.out.println(m.group());
        } else {
            System.out.println("Not found: " + text);
        }
    }
}

如您所见,此代码返回以下内容:

APLU4975723434
APLU4975723434
Not found: Viuhaskfdksjfkds  APLIC4975723434 fkdsjkfjaksjfklsdakldjsen
APLU49

并且在第一行上未找到(我希望这样做!)文本“ ABC123xyxyxyxyxyxyxyxyxyx”。

谢谢你的帮助!

if块内使用循环来覆盖测试字符串的任何其他实例。

if (m.find()) {
    System.out.print(m.group() + " ");
    while (m.find()) {
        System.out.print(m.group() + " ");
    }
} else {
    System.out.println("Not found: " + text);
}

暂无
暂无

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

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