如何设计正则表达式模式来匹配字符串

2024-10-05 12:17:10 发布

您现在位置:Python中文网/ 问答频道 /正文

import re
text = "**Company** [Click1](call:58200) ******provides*** **housekeeping** **clean***"
bold = re.findall(r'\*{2}(\w+?)\*{2}', text)
print bold

result: ['Company', 'provides', 'housekeeping', 'clean']
expect: ['**Company**', '**housekeeping**']

如何设计regex模式来grep它?你知道吗


Tags: textimportrecleanresultcallcompanyprovides
1条回答
网友
1楼 · 发布于 2024-10-05 12:17:10

你可以试试Lookaround

The lookaround actually matches characters, but then gives up the match, returning only the result: match or no match

(?<!\*)\*{2}\w+?\*{2}(?!\*)

Online demo

示例代码:

import re
p = re.compile(ur'(?<!\*)\*{2}\w+?\*{2}(?!\*)')
test_str = u"**Company** [Click1](call:58200) ******provides*** **housekeeping** **clean***"

re.findall(p, test_str)

图案说明:

  (?<!                     look behind to see if there is not: 
    \*                       '*'
  )                        end of look-behind

   \*{2}                    '*' (2 times)
  \w+?                     word characters (a-z, A-Z, 0-9, _) (1 or more times)
   \*{2}                    '*' (2 times)

   (?!                      look ahead to see if there is not:
     \*                       '*'
   )                        end of look-ahead

相关问题 更多 >

    热门问题