匹配* text *的正则表达式是什么?

时间:2012-05-27 12:48:15

标签: python regex

匹配this is *some text*.但不是this is \*another \*text的正则表达式是什么?正则表达式应该与星号之间的文本匹配。

1 个答案:

答案 0 :(得分:1)

pattern = "\*(\w+(?:\s+\w+)*)\*"
re.findall(pattern, "this is *some text*.") // return 'some text'
re.findall(pattern, "this is \*another \*text") // return nothing

用'$'代替'*':

subpattern = "(\*(\w+(?:\s+\w+)*)\*)"
re.sub(subpattern, r"$\2$", "this is *some text*.") // return 'this is $some text$.'