Java regex parentheses words

I have the following input line:

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

(line length and "something" is changing).

Required Conclusion:

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

I tried

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

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

Thanks!

+6
source share
4 answers

If I do not understand, you can match everything between quotation marks and replacement.

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

If you want to replace the space around == :

 s = s.replaceAll("\\s*==\\s*'([^']+)'", "==(\"$1\")"); 
+7
source
 (?<===)\s*'(\S+?)' 

Try it. Replace ("$1") . View the demo.

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

or

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

Try it. Check out the demo.

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

+2
source

You can do this in two steps replaceAll() :

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

Full example code:

 String str = "flag1 == 'hello' and flag2=='hello2'"; str = str.replaceAll("'(?=\\w)","('") .replaceAll("(?<=\\w)'$?", "')"); System.out.println(str); // prints flag1 == ('hello') and flag2==('hello2') 
+2
source

try it

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

Source: https://habr.com/ru/post/983779/


All Articles