【问题标题】:Matcher Class Java - Matching Multiple Sub-strings on Same LineMatcher Class Java - 匹配同一行上的多个子字符串
【发布时间】:2015-10-17 20:45:29
【问题描述】:

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

感谢您的帮助!

【问题讨论】:

    标签: java string matcher


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 2011-06-28
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多