Regex problem.

X

X. Lee

Hello, I am in need of some regex assistance..

In my project, I need to parse a String and replace everything within
brackets with the String "xx".

I thought this would be pretty simple, using the Pattern "(\[.+\])".

this pattern works fine if there is only one set of brackets in my
String, however it fails if I have multiple bracket sets because it
only seems to consider the very first and very last brackets found.

e.g.:

"This is my [test] String" becomes "This is my [xx] String" <-- fine

but "This is [my] other [test] String" also becomes "This is my [xx]
String" instead of "This is [xx] other [xx] String" <-- not fine

So the matcher finds "[my] other [test]" instead of finding [my] and
[test] separately.

How can I make it find each set of brackets separately?
 
S

sipayi

It does work if you reduce the narrow down the intermediate
characters...

System.out.println("This is [my] other [test]
String".replaceAll("[\\[][a-zA-Z0-9]+[\\]]", "xx"));

does print "This is xx other xx String". The ']' seems to be included
in ".+".

Just a thought.
-Siplin
 
F

Ferenc Hechler

try "(\[[^\]+])"
means: first "[", then sequence of chars except "]" and last "]"

the problem is that "+" and "*" are greedy, they take as much as they can.
There is a possipility to use the shortest match with an "?", but I am not
sure about the correct syntax.

bye,
feri
 
A

Alan Moore

the problem is that "+" and "*" are greedy, they take as much as they can.
There is a possipility to use the shortest match with an "?", but I am not
sure about the correct syntax.

You just add the '?' after the '*' or '+':

str = str.replaceAll("\\[.*?\\]", "[xx]");
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top