替换为图案

时间:2019-01-07 11:33:09

标签: python regex python-2.7

我尝试将==的模式替换为.equals(。但是,为了闭合括号),每次模式都可能不同时,我面临一个问题。那么我应该把什么作为基本标准?

对于下面的代码,我编写的模式工作正常,但是当模式更改时,例如,如果消息为:if ((var1 == null) || (var1.equals(""))) { var1 = "id";},则我的代码将失败。

message = '''if (var1 != null && var1 == "") var1 = null;'''

message = message.replace('==','.equals(')
result = re.sub('\&\&(.+?)\)', '\\1))', message)

我想要一种可以将==修改为.equals()而又不影响变量和现有代码的模式。

2 个答案:

答案 0 :(得分:0)

如果您正在寻找可以在100%的时间内使用的东西,那么您需要一个语言解析器。

但是,如果我没错,您只是想在大量代码上进行查找/替换,那么80%左右的内容还是可以接受的(并且您可以修复所有出错的内容),然后如下所示应符合您的需求:

([a-zA-Z]\w+|[)])(\s*==\s*("[^"]*"|\w+)(?=\s*[|;&)]))

您可以在替换字符串中使用组引用来获取组的内容,这将允许您保留匹配的内容。像这样:

$1.equals($3)

这将转换如下代码:

if ( foo == "bar" || foo == baz && foo == baz + 1 /*right hand side too complex*/ && bar == baz ){

  foo = baz( "bat" ) == bar;
  foo = bar == baz( "bat" ); // right hand side is too complex
  bar = 77 == 99; // left hand side is not a variable
  bar = bat == 99;
  bar = bat == 99.0; // floats not supported

}

对此:

if ( foo.equals("bar") || foo.equals(baz) && foo == baz + 1 /*right hand side too complex*/ && bar.equals(baz) ){

  foo = baz( "bat" ).equals(bar);
  foo = bar == baz( "bat" ); // right hand side is too complex
  bar = 77 == 99; // left hand side is not a variable
  bar = bat.equals(99);
  bar = bat == 99.0; // floats not supported

}

这是一个演示:https://regexr.com/461lm

请注意,这不会尝试在==的右侧是表达式的情况下执行更复杂的替换,但是它将处理简单的变量以及字符串和整数。

答案 1 :(得分:0)

好吧,到目前为止,我通过编写一个非常简单的函数来实现它,但是我当然想看看您需要更长的代码来确保其正常工作。我针对此进行的所有测试均有效。顺便说一句,我组合了“ regex”和“ replace”,因为replace很棒

输入

>>> def replace_equals(message):
        import re
        found_equals = list(set(re.findall('[\s]+==[\S\s]*?\)', message)))
        for i in range(len(found_equals)):
            edit_found_equals = found_equals[i].replace(' == ', '.equals(').replace(')', '))')
            message = message.replace(found_equals[i], edit_found_equals)
        print(message)

输出

1.
>>> message = '''if (var1 != null && var1 == "") var1 = null;'''
>>> replace_equals(message)
'if (var1 != null && var1.equals("")) var1 = null;'

2.
>>> message = '''if ((var1 == null) || (var1.equals(""))) { var1 = "id";}'''
>>> replace_equals(message)
'if ((var1.equals(null)) || (var1.equals(""))) { var1 = "id";}'

基本说明

我使用正则表达式(re.findall)查找每次出现的“ == [任意数量的字符并在您击中')']时终止,并将它们放在列表中。我遍历该列表,编辑找到的字符串,以将“ ==”替换为“ .equals(”和“)”并替换为“))”,然后在消息中查找我发现的原始字符串,并将其替换为我创建的字符串的新编辑。