繁体   English   中英

如何在 python 中的字符串中查找和替换整个单词(完全匹配),而字符串包含元字符?

[英]How to find and replace the whole word (exact match) from a string in python using “re” package while the string contains the metacharacter?

例如,

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

我只想在字符串中查找并替换"array[0]" 在这种情况下,假设我想用单词"element1"替换它。 那么output应该如下:

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

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

我感谢任何人的帮助。

尝试关注

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

Output:

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

Output:

'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[az]+\[[0-9]+\](?=[\s]{1})", "Element1", t)

您在正则表达式的末尾看到 - (?=[\s]{1}),第二个数组 [0] 后面没有空格,因此不会被替换。

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

Output:

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

演示和解释

import re

line = "array[0] is the first element, array[0]some_character, is not a valid element"
re.sub('array\[0\]\s','element1 ',line)

Output: 'element1 是第一个元素,array[0]some_character,不是有效元素'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM