rdi*_*503 11 python regex dollar-sign
如何提取以$符号开头的字符串中的所有单词?例如在字符串中
This $string is an $example
Run Code Online (Sandbox Code Playgroud)
我想提取单词$string和$example.
我尝试使用这个正则表达式,\b[$]\S*但只有当我使用普通字符而不是美元时才能正常工作.
fra*_*xel 22
>>> [word for word in mystring.split() if word.startswith('$')]
['$string', '$example']
Run Code Online (Sandbox Code Playgroud)
你的expr的问题是\b空格和a之间不匹配$.如果你删除它,一切正常:
z = 'This $string is an $example'
import re
print re.findall(r'[$]\S*', z) # ['$string', '$example']
Run Code Online (Sandbox Code Playgroud)
要避免匹配words$like$this,请添加一个lookbehind断言:
z = 'This $string is an $example and this$not'
import re
print re.findall(r'(?<=\W)[$]\S*', z) # ['$string', '$example']
Run Code Online (Sandbox Code Playgroud)
在\b逃生的字边界匹配,但$符号不字,你可以搭配深思熟虑的一部分.改为匹配起点或空格:
re.compile(r'(?:^|\s)(\$\w+)')
Run Code Online (Sandbox Code Playgroud)
我在这里使用了反斜杠转义符号而不是字符类,并且\w+使用了至少1个字符的单词字符类来更好地反映您的意图.
演示:
>>> import re
>>> dollaredwords = re.compile(r'(?:^|\s)(\$\w+)')
>>> dollaredwords.search('Here is an $example for you!')
<_sre.SRE_Match object at 0x100882a80>
Run Code Online (Sandbox Code Playgroud)