【发布时间】:2015-12-10 12:44:12
【问题描述】:
我想编写一个识别以下模式的java正则表达式。
abc def the ghi 和 abc def ghi
我试过了:
abc def (the)? ghi
但是,它无法识别第二种模式。我哪里出错了?
【问题讨论】:
标签: java regex regex-lookarounds
我想编写一个识别以下模式的java正则表达式。
abc def the ghi 和 abc def ghi
我试过了:
abc def (the)? ghi
但是,它无法识别第二种模式。我哪里出错了?
【问题讨论】:
标签: java regex regex-lookarounds
abc def (the )?ghi
^^
去掉多余的space
【讨论】:
abc def(\\sthe)? ghi
空格也是正则表达式中的有效字符,所以
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)
返回:res -> 记录
s = "abc def ghi"
res = re.search(x, s)
返回:res -> 记录
s = "abc Xef ghi"
res = re.search(x, s)
返回:res -> 无
【讨论】: