Link to home
Start Free TrialLog in
Avatar of ZOOMAY
ZOOMAY

asked on

help with regular expressions

Hi,

I require some help with the regular exp in java.

I have a String say
String test="regular +expr + java+ example";

I will get the String as  req parameter.
If I find space before and after " + " I will have to remove that and replace that to test="regular +expr+java+example";(without any spaces)
if there is space after "+ " then the String should become test="regular +expr+java+example";(without any spaces)
If I have space only before " +"it should stay as it is test="regular +expr+java+example";

The only condition when the "+" will remain unaltered is when it is preceded by space(s) and immediately followed by text with no space in between.i.e(regular +expr).

Please help me.

Thanks.

Avatar of colr__
colr__

if (!test.contains(" +"))
   test.removeAll(" ");
search for \+\s+
replace with +

You might be required to escape the "\" character in Java.
In fact it might be this:

if (!test.contains(" +") && !test.contains("+ "))
   test.removeAll(" ");

Is this what you are looking for?
Avatar of Mayank S
And since String is immutable:

String newTest = test.removeAll ( " " ) ;
test.replaceAll("\\+\\s*", "\\+");
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
(without the final bracket ;-))
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>there might be a lot of useless replaces

I doubt it, as that would be fairly incompetent of 'them' to try to replace a token with an identical one, but you're right - it'd be better to err on the safe side
Avatar of ZOOMAY

ASKER

Thanks a lot for the help.
:-)