如何在正则表达式中写可选词?
How to write optional word in Regular Expression?
我想编写一个 java 正则表达式来识别以下模式。
abc def the ghi
和 abc def ghi
我试过这个:
abc def (the)? ghi
但是,它无法识别第二个 pattern.Where 我是不是搞错了?
abc def (the )?ghi
^^
去掉多余的space
空格也是正则表达式中的有效字符,因此
abc def (the)? ghi
^ ^ --- spaces
只能匹配
abc def the ghi
^ ^---spaces
或者当我们删除 the
单词时
abc def ghi
^^---spaces
您需要像 abc def( the)? ghi
这样的东西来使其中一个空格成为可选的。
你的例子在 Python
中对我来说非常有效
x = "def(the)?"
s = "abc def the ghi"
res = re.search(x, s)
Returns: 资源 -> 记录
s = "abc def ghi"
res = re.search(x, s)
Returns: 资源 -> 记录
s = "abc Xef ghi"
res = re.search(x, s)
Returns: 资源 -> None
我想编写一个 java 正则表达式来识别以下模式。
abc def the ghi
和 abc def ghi
我试过这个:
abc def (the)? ghi
但是,它无法识别第二个 pattern.Where 我是不是搞错了?
abc def (the )?ghi
^^
去掉多余的space
空格也是正则表达式中的有效字符,因此
abc def (the)? ghi
^ ^ --- spaces
只能匹配
abc def the ghi
^ ^---spaces
或者当我们删除 the
单词时
abc def ghi
^^---spaces
您需要像 abc def( the)? ghi
这样的东西来使其中一个空格成为可选的。
你的例子在 Python
中对我来说非常有效 x = "def(the)?"
s = "abc def the ghi"
res = re.search(x, s)
Returns: 资源 -> 记录
s = "abc def ghi"
res = re.search(x, s)
Returns: 资源 -> 记录
s = "abc Xef ghi"
res = re.search(x, s)
Returns: 资源 -> None