Reputation: 917
I have following piece of code:
string.replace(",Target_String", ""));
The thing is that comma ,
can happen before and after the Target_String
and sometimes there can be space between comma and Target_String
.
I want to avoid code such as having four different replace
methods like:
string.replace(",Target_String", ""));
string.replace(", Target_String", ""));
string.replace("Target_String,", ""));
string.replace("Target_String ,", ""));
But I don't know how can I achive above functionality with regular expression.
Edit: comma can be found only at the end or the beggining - never on the both sides of the target_string
Upvotes: 0
Views: 200
Reputation: 3718
would this not be sufficient?
all commas would then be set uniformly in the line
"Target_String, blah , Target_String ,Target_String ,".replaceAll( "\\h*,\\h*", "," ) );
gets: Target_String,blah,Target_String,Target_String,
Upvotes: 0
Reputation: 784998
You may use this regex replaceAll
:
string = string.replaceAll(",?\\h*Target_String\\h*,?", "");
Explanation:
,?\\h
: Match optional comma followed by 0 or more horizontal spacesTarget_String
: Match literal text Target_String
\\h*,?
: Match 0 or more horizontal spaces followed by an optional commaUpvotes: 2
Reputation: 37404
You can use replaceAll
as
string.replaceAll(",\\s*Target_String\\s*,","");
\\s*
match zero or more space characters
if there's only one possibility of space then you can use ?
to represent a possible character occurrence.
string.replaceAll(",\\s?Target_String\\s?,","");
or use
string.replaceAll("[, ]*Target_String[, ]*","");
[, ]*
: match zero or more occurrences of ,
and space character
Upvotes: 1