简体   繁体   中英

Multi-line string search

Let's say the user provides a search query input:

word1 word2 word3

And the text that's being searched looks like:

Some text some text some text word1 \r\n (newline here)
word2      word3 some text some text some text.

Is there a way to turn the user's input into a regular expression and basically get an index of where the search query starts and ends, with dismaying the line breaks and multiple spaces?

You can do this in that way:

public static String regex = "//s+" +"((" + word1 + ")|(" + word2 + ")|(" + word3 + "))//s+"

public static void printMatches(String text, String regex) {
  Pattern pattern = Pattern.compile(regex);
  Matcher matcher = pattern.matcher(text);
  // Check all occurrences
  while (matcher.find()) {
    System.out.print("Start index: " + matcher.start());
    System.out.print(" End index: " + matcher.end());
    System.out.println(" Found: " + matcher.group());
  }
}

使用DOTALL标志来匹配跨越多行的文本。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM