簡體   English   中英

正則表達式字符串切片

[英]Regex String Slicing

如果使用正則表達式,則使用Python風格,並且在替換文本時需要切片字符串。 我用來匹配所需字符串的正則表達式是abc .+ cba 如果它與abc Hello, World cba匹配,則應更改為efg Hello, World

使用捕獲組:

>>> s = "here is some stuff abc Hello, World cba here is some more stuff"
>>> import re
>>> re.sub(r'abc (.+) cba', r'efg \1',s)
'here is some stuff efg Hello, World here is some more stuff'
>>>

注意:替換字符串接受反向引用。

您可以如下使用re.sub函數:

re.sub(pattern, repl, string, count=0, flags=0)

在repl中,支持使用\\ 1,\\ 2 ...使用()向后引用組1、2 ...中的模式匹配的字符串。 這次是(。+)

>>> import re
>>> re.sub(r"abc (.+) cba",r"efg \1", "abc Hello, World cba")
'efg Hello, World'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM