提取字符串中的项目

时间:2013-05-06 08:00:52

标签: java string indexing substring

我想在一个特定的字符串中提取Hello世界当前我得到的是第一个和最后一个Occurences.there里面有三(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);

1 个答案:

答案 0 :(得分: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());
} 

如果您只想在 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