-2

我想在一个特定的字符串中提取 Hello world,目前我得到了第一个和最后一个 Occurences。字符串中有 3(三个)hello world 文本,我希望它们在每个特定的字符串上。

String text="hellogfddfdfsdsworldhelloasaasasdasdggworldfdfdsdhellodasasddworld";
int x=text.indexOf("hello");
int y=text.indexOf("world");
String test=text.substring(x, y+4);
System.out.println(test);
x=text.indexOf("hello");
y=text.indexOf("world");
String test1=text.substring(x,y);
System.out.println(test1);
x=text.lastIndexOf("hello");
y=text.lastIndexOf("world);
String test2=text.substring(x, y);
System.out.println(test2);
4

1 回答 1

0

听起来像是正则表达式的工作。最简单的一个是

List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile(
    "hello # Match 'hello'\n" +
    ".*?   # Match 0 or more characters (any characters), as few as possible\n" +
    "world # Match 'world'", 
    Pattern.COMMENTS);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    matchList.add(regexMatcher.group());
} 

如果您只想要 and 之间的文本, 使用helloworld

Pattern regex = Pattern.compile(
    "hello # Match 'hello'\n" +
    "(.*?) # Match 0 or more characters (any characters), as few as possible\n" +
    "world # Match 'world'", 
    Pattern.COMMENTS);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    matchList.add(regexMatcher.group(1));
} 

请注意,如果模式可以嵌套,这将失败,即hello foo hello bar world baz world.

于 2013-05-06T08:03:47.350 回答