【发布时间】: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”。
感谢您的帮助!
【问题讨论】: