在字符串中两个单词之间查找文本

时间:2018-09-11 08:00:47

标签: java regex string arraylist regex-group

我有一个包含各种值的String列表。

 List<String> list = new ArrayList<(Arrays.asList("Hello", "Howdy", "Hi", "Good", "Binding"));

我有一个字符串变量:

String text = "Howdy mates my name is unknown Hello 
from the other side and Binding is a act punishable." 

(不介意文字)。

现在我想从字符串中找到列表中的值之间的文本。

例如,HowdyHello之间的文本是:mates my name is unknown

HelloBinding之间的类似文本:from the other side and

我尝试使用正则表达式来完成此操作:Java - Best way to grab ALL Strings between two Strings? (regex?) 但是问题是我必须给出前缀和后缀。 但是我希望程序从列表本身中查找。

我该怎么做?

3 个答案:

答案 0 :(得分:1)

这可能不是最好的答案,但仍然可以解决您的情况。

public String findBetween(String inputText,String from,String to) {
    String result = null;
    result = inputText.substring(inputText.indexOf(from) + from.length(),inputText.indexOf(to));
    return result;
}                             

答案 1 :(得分:0)

尝试以下模式:(Howdy)(.+)(?(1)(Hello))(.+)(?(3)Binding)

它在HowdyHello之间捕获文本到第二个捕获组,在HelloBinding之间捕获文本到第四个捕获组。

该模式按以下方式工作:将Howdy捕获到第一组。然后捕获所有异常,直到遇到Hello,但前提是找到Howdy。同样,如果匹配Binding,则捕获文本直到Hello

Demo

答案 2 :(得分:0)

绝对不是最优雅的解决方案,但它可以解决问题:

    List<String> list = new ArrayList<>(Arrays.asList("Hello", "Howdy", "Hi", "Good", "Binding"));
    List<List<String>> results = new ArrayList<>();

    String text = "Howdy mates my name is unknown Hello from the other side and Binding is a act punishable.";
    String[] words = text.split(" ");

    boolean wordsBetween = false;
    List<String> wordsList = new ArrayList<>();

    for (String word : words) {
        //after we found first word from list we add all words that are not on list into tmp wordsList
        if(!list.contains(word) && wordsBetween){
            wordsList.add(word);
        }

        //satisfied when we first find a word from list
        if (list.contains(word) && !wordsBetween) {
            wordsBetween = true;
            continue;
        }
        //satisfied for all next words from list
        //all words we added meantime into tmp wordsList are added also into results
        if (list.contains(word) && wordsBetween) {
            results.add(new ArrayList<>(wordsList));
            wordsList.clear();
        }

    }
    for (List listResult : results) {
        System.out.println(listResult);
    }