简体   繁体   English

正则表达式字符串切片

[英]Regex String Slicing

I am using Python flavor if regex, and I need to slice a string while replacing text. 如果使用正则表达式,则使用Python风格,并且在替换文本时需要切片字符串。 The regex I am using to match my needed string is this, abc .+ cba . 我用来匹配所需字符串的正则表达式是abc .+ cba If it matched abc Hello, World cba , that should change to efg Hello, World . 如果它与abc Hello, World cba匹配,则应更改为efg Hello, World

Use a capturing group: 使用捕获组:

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

Note: the replacement string accepts a backreference. 注意:替换字符串接受反向引用。

You can use the function re.sub as below: 您可以如下使用re.sub函数:

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

In repl, support use \\1, \\2 ... to backreference the string matched in pattern by group 1, 2 ..., using (). 在repl中,支持使用\\ 1,\\ 2 ...使用()向后引用组1、2 ...中的模式匹配的字符串。 For this time, it's (.+) 这次是(。+)

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