我有以下输入字符串:
flag1 == 'hello' and flag2=='hello2'
(字符串长度和 == 'something' 会有所不同)。
期望输出:
flag1==("hello") and flag2=("hello2")
我已经尝试过
line = line.replaceAll("(\\s*==\\s*)", "(\"")
但是这并没有给我右括号。有什么办法可以解决吗?谢谢!
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\")");
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')
(?<===)\s*'(\S+?)'
\s*==\s*'(\S+?)'
试一下这个。查看演示。
试试这个
s = s.replaceAll("(=\\s*)'(.*?)'", "$1(\"$2\")");
==周围的空格
? - vks