Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex enclose words in brackets

Tags:

java

regex

I have the following input string:

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

(the string length and == 'something' varies).

Desired output:

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

I have tried

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

but that does not give me the end bracket. Any idea how this can be done?

Thanks!

like image 369
user100001 Avatar asked Mar 14 '15 04:03

user100001


1 Answers

Unless I'm misunderstanding, you could match everything between the quotes and replace.

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

If you want the whitespace around == replaced:

s = s.replaceAll("\\s*==\\s*'([^']+)'", "==(\"$1\")");
like image 186
hwnd Avatar answered Sep 20 '22 03:09

hwnd