Python 在非字母数字字符之前匹配单词边界

Python 在非字母数字字符之前匹配单词边界,python,regex,Python,Regex,我想在re.findall 匹配词示例 不匹配单词示例 为什么\b不起作用 如果第一个字符是字母数字,我可以这样做 re.findall(r'\bA\w+', s) 但是这对于像\b\$\w+这样的模式不起作用,因为\b只在\w和\w之间匹配空字符串 # The line below matches only the last '$baz' which is the one that should not be matched re.findall(r'\b\$\w+', '$foo $bar

我想在
re.findall

匹配词示例 不匹配单词示例 为什么
\b
不起作用 如果第一个字符是字母数字,我可以这样做

re.findall(r'\bA\w+', s)
但是这对于像
\b\$\w+
这样的模式不起作用,因为
\b
只在
\w
\w
之间匹配空字符串

# The line below matches only the last '$baz' which is the one that should not be matched
re.findall(r'\b\$\w+', '$foo $bar x$baz').
上面的输出是
['$baz']
,但是所需的模式应该输出
['$foo','$bar']

我尝试用模式
^\s
替换
\b
,但这不起作用,因为lookarounds的长度必须固定


处理此模式的正确方法是什么?

一种方法是对非空白元字符
\S
使用负查找

s = '$Python $foo foo$bar baz'

re.findall(r'(?<!\S)\$\w+', s) # output: ['$Python', '$foo']
s='$Python$foo-foo$bar-baz'

关于findall(r’(?一种方法是对非空白元字符
\S
使用负查找

s = '$Python $foo foo$bar baz'

re.findall(r'(?<!\S)\$\w+', s) # output: ['$Python', '$foo']
s='$Python$foo-foo$bar-baz'

关于findall(r’(?以下内容将匹配以单个非字母数字字符开头的单词

re.findall(r'''
(?:     # start non-capturing group
  ^         # start of string
  |         # or
  \s        # space character
)       # end non-capturing group
(       # start capturing group
  [^\w\s]   # character that is not a word or space character
  \w+       # one or more word characters
)       # end capturing group
''', s, re.X)
或者只是:

re.findall(r'(?:^|\s)([^\w\s]\w+)', s, re.X)
结果:

'$a $b a$c $$d' -> ['$a', '$b']

以下内容将匹配以单个非字母数字字符开头的单词

re.findall(r'''
(?:     # start non-capturing group
  ^         # start of string
  |         # or
  \s        # space character
)       # end non-capturing group
(       # start capturing group
  [^\w\s]   # character that is not a word or space character
  \w+       # one or more word characters
)       # end capturing group
''', s, re.X)
或者只是:

re.findall(r'(?:^|\s)([^\w\s]\w+)', s, re.X)
结果:

'$a $b a$c $$d' -> ['$a', '$b']

您期望的输出是什么?可能是
re.findall(r'(?:\b | ^)\$\w+,“$a$a x$a”)
?正确,我刚刚发现反向查找有效:
(?您的示例不好。请使用类似
$a$b x$c
instead@anubhava它足够接近了,我只是用\s来表示lookback,而不是像“$$a”这样的词。你期望的输出是什么?也许
re.findall(r'(?:\b |^)\$\w+”,“$a$a x$a”)
?正确,我刚刚发现反向lookback是有效的:
(?您的示例不好。请使用类似
$a$b x$c
instead@anubhava它足够近了,我只是用\s作为lookback,而不是像“$$a”这样的单词,然后理解
\b
(单词边界)对你的正则表达式一开始不是正确的选择,因为
\bA\w+
也会匹配
-Afoo
好的,那么
\b
(单词边界)对你的正则表达式一开始不是正确的选择,因为
\bA\w+
也会匹配
-Afoo