簡體   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