在python中,当字符串包含元字符时,如何使用“re”包从字符串中查找和替换整个单词(精确匹配)?

2024-10-01 09:35:25 发布

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

比如说,

line = "array[0] is the first element, array[0]some_character, is not a valid element"

我只想找到并替换字符串中的"array[0]"。在本例中,假设我想用单词"element1"替换它。然后输出应如下所示:

line = "element1 is the first element, array[0]some_character, is not a valid element".

请注意,在字符串中,array[0]some_character应该保持不变,不应该像"element1some_character"那样替换它

我感谢任何人的帮助


Tags: the字符串islinenotsomeelement单词
3条回答
import re

line = "array[0] is the first element, second is array[0], array[0]some_character, is not valid element array[0]."
res = re.sub(r'\barray\[0\](?!\w)', 'REPL', line)
print res

输出:

REPL is the first element, second is REPL, array[0]some_character, is not valid element REPL.

说明:

\b              # word boundary, to not match isarray[0]
array\[0\]      # the string to match
(?!\w)          # negative lookahead, make sure we haven't a word character after

Demo & explanation

试着跟随

word = "abcd ab[0]c ab[0] class ab[0]d classified ab[0]"
re.sub(r'ab\[0\](\s|$)', r'ahmed\1', word)

输出:

'abcd ab[0]c ahmed class ab[0]d classified ahmed'

或者使用前瞻性

word = "abcd ab[0]c ab[0] class ab[0]d classified ab[0]"
re.sub(r'ab\[0\](?=\s|$)', r'ahmed', word)

输出:

'abcd ab[0]c ahmed class ab[0]d classified ahmed'

t = "array[0] is the first element, array[0]some_character, is not a valid element" re.sub("a[a-z]+\[[0-9]+\](?=[\s]{1})", "Element1", t)

您可以看到,在regex-(?=[\s]{1})的末尾,第二个数组[0]后面没有空格,因此它不会被替换

相关问题 更多 >