-2

特定の文字列内で Hello world を抽出したいのですが、現在、最初と最後の Occurences を取得しています。文字列内に 3 つ (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());
} 

との のテキストのみが必要な場合は、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 に答える