簡體   English   中英

多行字符串搜索

[英]Multi-line string search

假設用戶提供了搜索查詢輸入:

word1 word2 word3

被搜索的文本如下所示:

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

有沒有一種方法可以將用戶的輸入轉換為正則表達式,並從根本上獲得搜索查詢開始和結束的位置的索引,而使換行符和多個空格令人沮喪?

您可以通過以下方式執行此操作:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM