Java正则表达式将单词括在括号中

Java正则表达式将单词括在括号中,java,regex,Java,Regex,我有以下输入字符串: flag1 == 'hello' and flag2=='hello2' (字符串长度和=='something'不同) 期望输出: flag1==("hello") and flag2=("hello2") 我试过了 line = line.replaceAll("(\\s*==\\s*)", "(\"") 但这并没有给我最后的括号。你知道怎么做吗 谢谢 (?<===)\s*'(\S+?)' 试试这个。看演示 您可以通过replaceAll()的两个步骤来

我有以下输入字符串:

flag1 == 'hello' and flag2=='hello2'
(字符串长度和=='something'不同)

期望输出:

flag1==("hello") and flag2=("hello2")
我试过了

line = line.replaceAll("(\\s*==\\s*)", "(\"") 
但这并没有给我最后的括号。你知道怎么做吗

谢谢

(?<===)\s*'(\S+?)'
试试这个。看演示


您可以通过
replaceAll()的两个步骤来完成:


str.replaceAll(“(?=\\w)”,“(”).replaceAll((?除非我有误解,否则您可以匹配引号和replace之间的所有内容

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\")");
试试这个

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

我用@hwnd的方法来做这件事。谢谢所有回答:)但是那怎么替换==
@vks周围的空格呢?我用一个替换来替换==周围的空格()我的正则表达式在第一次尝试中就一次性完成了:)
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\")");
    s = s.replaceAll("(=\\s*)'(.*?)'", "$1(\"$2\")");