-2

I trying to use regex within the replaceAll function. I need to do a real simple task which is to switch ever = and ~ operator with a : char with no spaces!

For instance:

(srcIP = 0.0.0.0) AND (dstIP~0.0.0.0 OR protocol  =     TCP)

turns to

(srcIP:0.0.0.0) AND (dstIP:0.0.0.0 OR protocol:TCP)

I am trying to use the following code

query.replaceAll("[ ]*(=|~)[ ]*", ":");

but it doesn't work. Is there any way to do this using replaceAll function? It seems that it doesn't work with regex.

1
  • replaceAll and replace don't change the String, they create a new one. Commented Aug 21, 2016 at 8:48

2 Answers 2

2

Your regex is fine (although it can be improved). Proof:

System.out.println("(srcIP = 0.0.0.0) AND (dstIP~0.0.0.0 OR protocol = TCP)".replaceAll("[ ]*(=|~)[ ]*", ":"));

Prints:

(srcIP:0.0.0.0) AND (dstIP:0.0.0.0 OR protocol:TCP)

Strings are immutable in Java, replaceAll doesn't modify the string in-place, it returns a new one. You're probably not assigning the result back.

Your regex can be rewritten as:

\\s*[=~]\\s*
Sign up to request clarification or add additional context in comments.

1 Comment

You are absolutely right I forgot it is immutable thanks.
0

This

System.out.println("(srcIP = 0.0.0.0) AND (dstIP~0.0.0.0 OR protocol = TCP)".replaceAll("[ ]*(=|~)[ ]*", ":")); 

works fine for me

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.