Java正则表达式用括号括起来

时间:2015-03-14 04:19:43

标签: java regex

我有以下输入字符串:

flag1 == 'hello' and flag2=='hello2'

(字符串长度和=='某事'变化)。

期望的输出:

flag1==("hello") and flag2=("hello2")

我试过了

line = line.replaceAll("(\\s*==\\s*)", "(\"") 

但这并没有给我一个结束。知道如何做到这一点?

谢谢!

4 个答案:

答案 0 :(得分:7)

除非我误解,否则你可以匹配引号之间的所有内容并替换。

String s = "flag1 == 'hello' and flag2=='hello2'";
s = s.replaceAll("'([^']+)'", "(\"$1\")");
System.out.println(s); // flag1 == ("hello") and flag2==("hello2")

如果您想要替换==周围的空格:

s = s.replaceAll("\\s*==\\s*'([^']+)'", "==(\"$1\")");

答案 1 :(得分:2)

(?<===)\s*'(\S+?)'

试试这个。("$1")。见。演示。

https://regex101.com/r/oC3qA3/6

\s*==\s*'(\S+?)'

试试这个。看看演示。

https://regex101.com/r/oC3qA3/7

答案 2 :(得分:2)

您可以分两步执行replaceAll()

str.replaceAll("'(?=\\w)","('").replaceAll("(?<=\\w)'$?", "')");

完整代码示例:

String str = "flag1 == 'hello' and flag2=='hello2'";
str = str.replaceAll("'(?=\\w)","('")
         .replaceAll("(?<=\\w)'$?", "')");

System.out.println(str); // prints flag1 == ('hello') and flag2==('hello2')

答案 3 :(得分:2)

试试这个

    s = s.replaceAll("(=\\s*)'(.*?)'", "$1(\"$2\")");