简体   繁体   English

匹配字符串开头,中间和结尾的完整单词

[英]Match complete word at start, middle and end of string

How to replace the complete word abc.def at start, middle and end of string but do not replace the text like abc.def.au or d.abc.def : 如何在字符串的开头,中间和结尾替换完整的单词abc.def ,但不替换abc.def.aud.abc.def类的文本:

line = "abc.def abc.def.au abc.def d.abc.def abc.def"
new_line = re.sub("abc.def", "-----", line)
print(line)
print(new_line)

Current output: 电流输出:

abc.def abc.def.au abc.def d.abc.def abc.def
----- -----.au ----- d.----- -----

Expected output: 预期产量:

abc.def abc.def.au abc.def d.abc.def abc.def
----- abc.def.au ----- d.abc.def -----

Can this be done in one re.sub() ? 可以在一个re.sub()吗?

You can use line anchors. 您可以使用线锚。 ^ and $ matches only a the start of the string and end of the string respectively, so you could use them like such: ^$仅匹配字符串的开头和字符串的结尾,因此您可以像这样使用它们:

line = "abc.def abc.def.au abc.def d.abc.def abc.def"
new_line = re.sub(r"^abc\.def|abc\.def$", "-----", line)
print(line)
print(new_line)

Note that it is safer to raw regex strings, and escape the . 请注意,使用原始正则表达式字符串更安全,并转义. character (which matches almost any character in regex). 字符(几乎匹配正则表达式中的任何字符)。


If you want to replace only whole words you will need some lookarounds instead: 如果您只想替换整个单词,则需要一些环视方法:

line = "abc.def abc.def.au abc.def d.abc.def abc.def"
new_line = re.sub(r"(?<!\S)abc\.def(?!\S)", "-----", line)
print(line)
print(new_line)

ideone demo ideone演示

(?<!\\S) will prevent a match if abc.def is preceded by a non-space character. 如果abc.def前面带有非空格字符,则(?<!\\S)将阻止匹配。

(?!\\S) will prevent a match if abc.def is followed by a non-space character. (?!\\S)将阻止匹配,如果abc.def后跟非空格字符。

暂无
暂无

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

相关问题 用开始和结束词分割字符串 - Split String with Start and End word 正则表达式匹配句子开头、结尾和中间的有效单词 - Regular expression to match valid words at start, end and in the middle of a sentence Python正则表达式匹配开始和结束字符串,并且必须包含特定的单词 - Python regular expression match start and end string and must contain specific word 正则表达式不匹配字符串末尾的整个单词(bigram),仅在开头和中间 - Regex not matching a whole word (bigram) at the end of a string, only at the beginning and middle 如何将字符串与中间的任何单词匹配,并将其存储为变量? - How do I match a string with any word in the middle, and store it as a variable? python regex匹配并替换字符串的开头和结尾,但保持中间 - python regex match and replace beginning and end of string but keep the middle python 正则表达式匹配直到单词如果找到单词否则匹配完整字符串并且匹配组将大于 0 - python Regex match till word if word found else match complete string and match group will be greater then 0 &#39;(match_start1)...(match_start2)...(match_end)&#39;查找最短的字符串匹配项 - '(match_start1)…(match_start2)…(match_end)' find the shortest string match 根据字符串python的start关键字和end关键字切割一个字符串 - Cutting a string based on the start keyword and end key word of the string python 用于检查字符串中单词的开头和结尾的python正则表达式 - python regular expression to check start and end of a word in a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM