简体   繁体   中英

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

For example,

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

I just want to find and replace "array[0]" in the string. In this case, let's assume, I want to replace it with the word "element1" . Then the output should be as follows:

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

Please notice that, in the string, array[0]some_character should be unchanged, it should not be replaced like "element1some_character"

I appreciate anyone's help.

Try following

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'

Or Using look-ahead

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)

you see at the end of regex - (?=[\s]{1}), no white space followed the second array[0], so it won't be replaced.

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.

Explanation:

\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

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 is the first element, array[0]some_character, is not a valid element'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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