• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 261
  • Last Modified:

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.

0
ZOOMAY
Asked:
ZOOMAY
  • 5
  • 2
  • 2
  • +2
2 Solutions
 
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
 
colr__Commented:
In fact it might be this:

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

Is this what you are looking for?
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Mayank SAssociate Director - Product EngineeringCommented:
And since String is immutable:

String newTest = test.removeAll ( " " ) ;
0
 
CEHJCommented:
test.replaceAll("\\+\\s*", "\\+");
0
 
CEHJCommented:
Of course that would be

test = test.replaceAll("\\+\\s*", "\\+"));
0
 
CEHJCommented:
(without the final bracket ;-))
0
 
enachemcCommented:
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

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now