必须使用正则表达式在java中编写
我需要在"what is"
之后打印一个单词
输入:
So what is java regex
what is operator in java
输出:
java
operator
答案 0 :(得分:1)
只需使用一个lookbehind来匹配一个字符串,该字符串紧跟在与lookbehind内部模式匹配的字符串之后。
(?<=what is )\\S+
OR
(?<=what\\sis\\s)\\S+
代码:
String s = "So what is java regex\n" +
"what is operator in java";
Pattern regex = Pattern.compile("(?<=what is )\\S+");
Matcher matcher = regex.matcher(s);
while(matcher.find()){
System.out.println(matcher.group(0));
}
输出:
java
operator
答案 1 :(得分:1)
如果必须是正则表达式,我会保持简单并使用capturing group来匹配并捕获“what is”之后的单词
what\sis\s(\w+)
注意:您需要引用匹配组#1
来返回匹配结果。
说明:
what # 'what'
\s # whitespace (\n, \r, \t, \f, and " ")
is # 'is'
\s # whitespace (\n, \r, \t, \f, and " ")
( # group and capture to \1:
\w+ # word characters (a-z, A-Z, 0-9, _) (1 or more times)
) # end of \1