Reputation: 29
I am very new to java and was currently having the below requirement.
Whenever i found 12.1
in a string it should be removed but it is conditional. for Eg Below
12.1,ztel,presto
should be ztel,presto
12.1
should be replaced as blank
12.1/7.1
should not do anything as it is separate value
I tried doing stringValue.replace("12.1","");
Mostly the requirement is if 12.1
is found comma separated or only 12.1
it should be replaced as blank else not.
The above code was working partially and not working for all conditions.
Please guide and help me learn. Thanks a lot.
Upvotes: 0
Views: 3639
Reputation: 12346
The first argument of String.replaceAll
is a regex. Did you consider,
yourString.replaceAll("12\\.1,?", "");
Now it will only use .
and not "any character" as a .
would do. It also will match the comma, if present.
If you cannot have it followed by something specific, you can use a negation.
yourString.replaceAll("12\\.1,?[^/]", "");
That would leave 12.1/7.1
.
Upvotes: 1
Reputation: 2323
if 12.1
that should be replaced as blank is the only word in that string you can use this:
stringValue.replaceAll("^12\\.1$","blank");
then replace again that string with this to replace the one separated with coma:
stringValue.replaceAll("12\\.1,","");
the final code will be like this :
stringValue= stringValue.replaceAll("^12\\.1$","blank").replaceAll("12\\.1,","");
note: ^ mean start of line while $ mean end of a line
Upvotes: 0
Reputation: 725
Sounds like a good use case for a regex! You can try out different regular expressions to match your data at regexr.
I would start with something like
^[\d\.]+,?
^
[]
containing digits \d
or dots \.
(you have to escape since .
is a special character)+
,?
You'll need to do something about not matching an entry containing a slash /
- I'm not sure how to handle that.
Upvotes: 0
Reputation: 326
You can try like this stringValue.replace( "12.1," , ""); Use comma after 12.7 in the first parameter.
Upvotes: 1