Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式包含;《泰晤士报》;但不是",;时钟“;_Python_Regex - Fatal编程技术网

Python 正则表达式包含;《泰晤士报》;但不是",;时钟“;

Python 正则表达式包含;《泰晤士报》;但不是",;时钟“;,python,regex,Python,Regex,免责声明:我知道可以使用“in”和“not in”,但由于技术限制,我需要使用regex 我有: a = "digital clock time fan. Segments featuring digital 24 hour oclock times. For 11+" b = "nine times ten is ninety" 我想根据包含的“times”而不是“oclock”进行匹配,所以a和b通过正则表达式,只有b通过 有什么想法吗?您可以使用以下方法: ^(?!.*\bo?clock

免责声明:我知道可以使用“in”和“not in”,但由于技术限制,我需要使用regex

我有:

a = "digital clock time fan. Segments featuring digital 24 hour oclock times. For 11+"
b = "nine times ten is ninety"
我想根据包含的“times”而不是“oclock”进行匹配,所以a和b通过正则表达式,只有b通过

有什么想法吗?

您可以使用以下方法:

^(?!.*\bo?clock\b).*\btimes\b
说明:

^                 # starting at the beginning of the string
(?!               # fail if
   .*\bo?clock\b    # we can match 'clock' or 'oclock' anywhere in the string
)                 # end if
.*\btimes\b       # match 'times' anywhere in the string
\b
用于单词边界,因此您仍然可以匹配字符串,如
“时钟时间”
,但如果匹配字符串,如
“分时度假”
,则会失败。如果不希望出现这种行为,可以删除正则表达式中的所有
\b

例如:

>>> re.match(r'^(?!.*\bo?clock\b).*\btimes\b', a)
>>> re.match(r'^(?!.*\bo?clock\b).*\btimes\b', b)
<_sre.SRE_Match object at 0x7fc1f96cc718>
重新匹配(r'^(?。*\bo?时钟\b.*\b时间\b',a) >>>重新匹配(r'^(?。*\bo?时钟\b.*\b时间\b',b) 也可以在Java中使用(我看到了标有“python”的问题)