【问题标题】:Python Regex Match WillCard as the end of a wordPython Regex 匹配 WillCard 作为单词的结尾
【发布时间】:2014-11-18 16:55:34
【问题描述】:

我正在尝试使用正则表达式来查看是否有一个包含'*''*' 的字符串的单词既不能是单词的开头,也不能是单词的中间;

例如:

ip* -> match
ip*5p -> not match
*ip -> not match
this is ip* -> match
give me *ip not here -> not match

我尝试了表达:

p = r'(?!\*).*\b\*'

但在“ip*5p”的情况下它失败了,它认为它是匹配的。

但如果我添加“词尾”即 '\b'

p = r'(?!\*).*\b\*\b'

在所有情况下都失败了,因为什么也没找到。

我也试过了

p = r'(?!\*)\b.*\*'

但仍然无法正常工作。 有什么提示吗?

注意:字符串必须只有一个 * 符号。

【问题讨论】:

  • 字符串可以包含多少个* 字符?总是只有一个吗?
  • @AvinashRaj 是的,这是一场比赛
  • 您是要捕获整个字符串,还是只捕获以星号结尾的单词?
  • 那你选错了答案,@JudyJiang。如果星号不止一个,Avinash Raj 的任何一种模式都不会打破这种模式。

标签: python regex word wildcard


【解决方案1】:

您可以使用下面的正则表达式,它使用积极的前瞻断言。

r'.*\S*\*(?=\s|$).*'

r'.*?\*(?=\s|$).*'

DEMO

>>> import re
>>> s = """ip*
... ip*5p
... *ip
... this is ip*
... give me *ip not here"""
>>> for i in re.findall(r'.*\S*\*(?=\s|$).*', s):
...     print(i)
... 
ip*
this is ip*

\*(?=\s|$) POsitive lookahead 断言符号 * 后面的字符必须是空格字符或行尾锚点 $

【讨论】:

    【解决方案2】:

    你说过:

    1. 您只想匹配末尾有* 的字符串。

    2. * 在字符串中只能出现一次。

    这意味着正则表达式是多余的。您需要做的就是计算* 字符的数量,然后测试* 是否在字符串的末尾:

    match = mystr.count('*') == 1 and mystr[-1] == '*'
    # or
    match = mystr.count('*') == 1 and mystr.endswith('*')
    

    如下所示,这适用于所有示例字符串:

    >>> mystr = 'ip*'
    >>> mystr.count('*') == 1 and mystr[-1] == '*'
    True
    >>> mystr = 'ip*5p'
    >>> mystr.count('*') == 1 and mystr[-1] == '*'
    False
    >>> mystr = '*ip'
    >>> mystr.count('*') == 1 and mystr[-1] == '*'
    False
    >>> mystr = 'this is ip*'
    >>> mystr.count('*') == 1 and mystr[-1] == '*'
    True
    >>> mystr = 'give me *ip not here'
    >>> mystr.count('*') == 1 and mystr[-1] == '*'
    False
    >>>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      • 2018-01-15
      • 1970-01-01
      相关资源
      最近更新 更多