[英]Replace second and last second characters, using re.sub
I have a string "F(foo)"
, and I'd like to replace that string with "F('foo')"
. 我有一个字符串
"F(foo)"
,我想用"F('foo')"
替换该字符串。 I know we can also use regular expression in the second parameter and do this replacement using re.sub(r"F\\(foo\\)", r"F\\('foo'\\)",str)
. 我知道我们也可以在第二个参数中使用正则表达式,并使用
re.sub(r"F\\(foo\\)", r"F\\('foo'\\)",str)
替换。 But the problem here is, foo is a dynamic string variable. 但是这里的问题是,foo是一个动态字符串变量。 It is different every time we want to do this replacement.
每次我们要进行替换时,情况都会有所不同。 Is it possible by some sort of regex, to do such replacement in a cleaner way?
是否可以通过某种正则表达式以更清洁的方式进行此类替换?
I remember one way to extract foo using ()
and then .group(1)
. 我记得一种使用
()
然后使用.group(1)
提取foo的方法。 But this would require me to define one more temporary variable just to store foo. 但这需要我再定义一个临时变量以存储foo。 I'm curious if there is a way by which we can replace
"F(foo)"
with "F('foo')"
in a single line or in other words in a more cleaner way. 我很好奇是否有一种方法可以单行或用更简洁的方式用
"F('foo')"
替换"F(foo)"
。
Examples : 例子 :
F(name)
should be replaced with F('name')
. F(name)
应该替换为F('name')
。 F(id)
should be replaced with F('id')
. F(id)
应替换为F('id')
。 G(name) should not be replaced. G(name)不应替换。 So, the regex would be
r"F\\((\\w)+\\)"
to find such strings. 因此,正则表达式为
r"F\\((\\w)+\\)"
以查找此类字符串。
Using re.sub
使用
re.sub
Ex: 例如:
import re
s = "F(foo)"
print(re.sub(r"\((.*)\)", r"('\1')", s))
Output: 输出:
F('foo')
The following regex encloses valid [Python|C|Java] identifiers after F and in parentheses in single quotation marks: 以下正则表达式将有效的[Python | C | Java]标识符括在F之后,并在括号中用单引号引起来:
re.sub(r"F\(([_a-z][_a-z0-9]+)\)", r"F('\1')", s, flags=re.I)
#"F('foo')"
There are several ways, depending on what foo actually is. 有几种方法,取决于foo实际是什么。 If it can't contain
(
or )
, you can just replace (
with ('
and )
with ')
. 如果它不能包含
(
或)
,只需更换(
与('
和)
与')
Otherwise, try using 否则,请尝试使用
re.sub(r"F\((.*)\)", r"F('\1')", yourstring)
where the \\1
in the replacement part will reference the (.*)
capture group in the search regex 其中替换部分中的
\\1
将引用搜索正则表达式中的(.*)
捕获组
In your pattern F\\((\\w)+\\)
you are almost there, you just need to put the quantifier +
after the \\w
to repeat matching 1+ word characters. 在模式
F\\((\\w)+\\)
您几乎已经到了,您只需要在\\w
后面加上量词+
即可重复匹配1+个单词字符。
If you put it after the capturing group, you repeat the group which will give you the value of the last iteration in the capturing group which would be the second o
in foo. 如果将其放在捕获组之后,请重复该组,这将为您提供捕获组中最后一次迭代的值,该值将是foo中的第二个
o
。
You could update your expression to: 您可以将表达式更新为:
F\((\w+)\)
And in the replacement refer to the capturing group using \\1
并在替换中使用
\\1
指代捕获组
F('\1')
For example: 例如:
import re
str = "F(foo)"
print(re.sub(r"F\((\w+)\)", r"F('\1')", str)) # F('foo')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.