2013-04-12 29 views
1

我想用文字2之间的所有文本(第一个字是固定的[大],但第2个或者是2个字[二]或[三])。查找单词之间的文本在Java中

注意 ::发现的文本和第二个词之间可能有或没有空格。 例如:

One  i am 
here 
Two 
i am fine 
One  i am 
here 
Two 
i am fine 
One  i am 
here 
Three 
i am fine 
One  i am 
here 
Two 
i am fine 

我发现什么是

Pattern p = Pattern.compile("(?<=\\bOne\\b)(.*?)(?=\\bTwo\\b)"); 

但由于它需要完整的单词,这是不正确的。

“二” 是有效的。
“fineTwo” 是无效的。

+0

你回顾后似乎无效。尝试:(?<= One)(。*?)(?= \\ b(?:Two | Three)\\ b)' – anubhava

回答

3

它只能在完整的单词匹配,因为你用字边界\b。如果你想接受“fineTwo”,然后取下第一边界

Pattern p = Pattern.compile("(?<=\\bOne\\b)(.*?)(?=Two\\b)"); 

能够接受“二”或“三”为结束,用交替:

Pattern p = Pattern.compile("(?<=\\bOne\\b)(.*?)(?=(?:Two|Three)\\b)"); 
0

试试这个:

for(String parseOne : Input.split("One")) 
    for (String parseTwo : parseOne.split("Two")) 
    for (String parseThree : parseTwo.split("Three")) 
     System.out.println(parseThree.replace("One", "").replace("Two", "").replace("Three", "").trim()); 
0

getTextBetweenTwoWords方法可以正常工作。

public static void main(String[] args) 
{ 
    String firstWord = "One"; 
    String secondword = "Two"; 
    String text = "One Naber LanTwo"; 
    System.out.println(getTextBetweenTwoWords(firstWord, secondword, text)); 
} 
private static String getTextBetweenTwoWords(String firstWord, String secondword, String text) 
{ 
    return text.substring(text.indexOf(firstWord) + firstWord.length(), text.indexOf(secondword)); 
}