用包含“或”的单词序列编写正则表达式

时间:2011-04-26 20:50:55

标签: regex

我想提取与"or"相关的一系列单词。例如,来自

 "there or is or a or problem with my computer"

我想提取

"there or is or a or problem"

我有正则表达式

(("[^"]+"+|.[^\s*]+)\s+or\s+)+("[^"]+"+|.[^\s*]+)

但表达式给出了以下结果:

"there or is", " a or problem or with"

打破单个字符。这个表达有什么不对吗?

2 个答案:

答案 0 :(得分:0)

连接的是字母拼写的单词,可以是:

\w+(?:\s+or\s+\w+)*

这将返回

"there or is or a or problem",  "with", "my", "computer"

如果你真的只想要那些至少有一个or的人,就像你的例子一样,

\w+(?:\s+or\s+\w+)+

将返回

"there or is or a or problem"

答案 1 :(得分:0)

尝试以下方法:

[\w\s]+or\s+\w+

注意,这将与以下突出显示的内容相匹配:

我的计算机出现或出现问题,或者我正在疯狂

但是,如果你想要那里或者是或者有问题计算机或我,请选择:

(\w+(?:\s+or\s+\w+)+)
相关问题