[英]In python using Regex, how do I insert a string after a string with a close-parenthesis character?
I have lines of data like this: 我有这样的数据行:
(ABCD:0.00825830327156463345,(LKSDJF:0.00000254996576400768,SDFADS:0.00917039554517301569):0.16367666117488463562,OIUO:0.00401845774067355072):0.0;
((OIUO:0.00298782818816040099,SDFADS:0.00148583412998809050):0.27857371651571366522,ABCD:0.00188545323182991121,LKSDJF:0.00799482946501124843):0.0;
And I am trying to use regex to insert a string after every every "):randomfloatingpoint_number". 而且我正在尝试使用正则表达式在每个“):randomfloatingpoint_number”之后插入一个字符串。 Sometimes the number is following by a comma and sometimes by a semicolon. 有时数字后跟逗号,有时后跟分号。
This is the code I wrote: 这是我写的代码:
line = re.sub(r"):[0-9\.])",r"\1 " + string, line)
But I get an error message that the parenthesis are unbalanced: 但是我收到一条错误消息,指出括号不平衡:
Traceback (most recent call last):
File "AssignFGbranches.py", line 31, in <module>
line = re.sub(r"):[0-9\.])",r"\1 " + string, line)
File "/usr/lib/python2.7/re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/usr/lib/python2.7/re.py", line 242, in _compile
raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis
What am I doing wrong? 我究竟做错了什么?
Thanks! 谢谢!
You need to escape the brackets. 您需要逃脱括号。 Also, there is no number that is immediately followed by a closing brace. 另外,没有数字后紧跟一个右花括号。 You may want something like this: 您可能想要这样的东西:
(\):[0-9.]+[;,])
This will match the following: 这将匹配以下内容:
554517301569 ):0.16367666117488463562,
OIUO 554517301569 ):0.16367666117488463562,
OIUO
There are two issues. 有两个问题。 One is that the literal close parens needs to be escaped. 一是字面量接近的括号需要被转义。 The other is that the open parens for the group was missing: 另一个是缺少该组的开放式括号:
re.sub(r"(\):[0-9\.]+)",r"\1 " + string, line1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.