[英]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标志来匹配跨越多行的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.