匹配非字母数字ch前的单词边界

2024-06-16 13:38:44 发布

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

我想在带有re.findall的字符串中找到以单个非字母数字字符开始的单词,比如'$'

匹配词示例

$Python
$foo
$any_word123

不匹配单词示例

$$Python
foo
foo$bar

为什么\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的长度必须是固定的。你知道吗

处理这种模式的正确方法是什么?你知道吗


Tags: the字符串re示例foo字母模式bar
2条回答

以下内容将匹配以单个非字母数字字符开头的单词。你知道吗

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']

一种方法是对非空白元字符\S使用负lookback。你知道吗

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

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

相关问题 更多 >