Regex 查找正则表达式匹配项&;拆下火柴的外部
我有一根绳子Regex 查找正则表达式匹配项&;拆下火柴的外部,regex,python-3.x,string,Regex,Python 3.x,String,我有一根绳子 content = "std::cout << func(some_val) << std::endl; auto i = func(some_other_val);" 所以我试过这个: 重新导入 content=“std::cout您应该捕获要保留在组中的匹配部分: re.compile(r'func\(([a-zA-Z0-9_]+)\)') 在这里,我将它捕获到第1组 然后您可以使用\1引用组1: print(c.sub(r'\1', content
content = "std::cout << func(some_val) << std::endl; auto i = func(some_other_val);"
所以我试过这个:
重新导入
content=“std::cout您应该捕获要保留在组中的匹配部分:
re.compile(r'func\(([a-zA-Z0-9_]+)\)')
在这里,我将它捕获到第1组
然后您可以使用\1
引用组1:
print(c.sub(r'\1', content))
请注意,一般情况下,您不应该使用正则表达式来解析非常规语言(如本例中的C)的源代码使用正则表达式。它可能在一些非常特殊的情况下工作,其中输入非常有限,但是您仍然应该使用C解析器来解析C代码。我已经找到了诸如and之类的库。您可以使用re.sub
来替换所有外部func(…)
仅使用如下值,请参阅正则表达式,这里我使用了[w]+
,如果您使用
import re
regex = r"func\(([\w]+)\)"
test_str = "std::cout << func(some_val) << std::endl; auto i = func(some_other_val);"
subst = "\\1"
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
重新导入
regex=r“func\([\w]+)\”
test_str=“std::cout”
import re
regex = r"func\(([\w]+)\)"
test_str = "std::cout << func(some_val) << std::endl; auto i = func(some_other_val);"
subst = "\\1"
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
std::cout << some_val << std::endl; auto i = some_other_val;