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.

ZOOMAYAsked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
Of course that would be

test = test.replaceAll("\\+\\s*", "\\+"));
0
 
colr__Commented:
if (!test.contains(" +"))
   test.removeAll(" ");
0
 
enachemcCommented:
search for \+\s+
replace with +

You might be required to escape the "\" character in Java.
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
colr__Commented:
In fact it might be this:

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

Is this what you are looking for?
0
 
Mayank SAssociate Director - Product EngineeringCommented:
And since String is immutable:

String newTest = test.removeAll ( " " ) ;
0
 
CEHJCommented:
test.replaceAll("\\+\\s*", "\\+");
0
 
CEHJCommented:
(without the final bracket ;-))
0
 
enachemcConnect With a Mentor Commented:
CEHJ,
it should be
test.replaceAll("\\+\\s+", "\\+");

because if you use * instead of +, there might be a lot of useless replaces (like replace "+" with "+")
0
 
CEHJCommented:
>>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
0
 
ZOOMAYAuthor Commented:
Thanks a lot for the help.
0
 
CEHJCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.