这是代码:
String Str ="Animals \n" +
"Dog \n" +
"Cat \n" +
"Fruits \n" +
"Apple \n" +
"Banana \n" +
"Watermelon \n" +
"Sports \n" +
"Soccer \n" +
"Volleyball \n";
Str
基本上有 3 个类别(动物、水果、运动)。他们每个人都在单独的队伍中。使用正则表达式,如何找到 Fruits 的内容,这将给我这样的输出:
Apple
Banana
Watermelon
我也想要一个与您的答案相匹配的解释,以便我更好地理解这个问题。
谢谢。 :)
最佳答案
假设您想要提取单词“Fruits”和单词“Sports”之间的文本,您可以使用带有 capturing group 的正则表达式。 。这样,如果字符串匹配,那么您仍然需要提取 group其中包含您想要的文本。
例如:
Pattern p = Pattern.compile("Fruits(.*?)Sports", Pattern.DOTALL);
// The string "Fruits" ------^ ^ ^ ^
// Capture everything in between --^ ^ ^
// The string "Sports" -----------------^ ^
// This tells the regex to treat newlines ^
// like normal characters ---------------------^
请参阅railroad diagram如下:
或者,您可以使用更高级的正则表达式 positive lookahead and lookbehinds 。这意味着您可以使正则表达式仍然查找单词“Fruit”和“Sports”之间的文本,但不将这些字符串本身视为匹配的一部分。
Pattern p = Pattern.compile("(?<!Fruits).*?(?=Sports)", Pattern.DOTALL);
关于java - 如何使用 Reg-ex 查找一组单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15148511/