Lenny
Lenny

Reputation: 917

Regex ignore white space

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

Answers (5)

Kaplan
Kaplan

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

anubhava
anubhava

Reputation: 784998

You may use this regex replaceAll:

string = string.replaceAll(",?\\h*Target_String\\h*,?", "");

RegEx Demo

Explanation:

  • ,?\\h: Match optional comma followed by 0 or more horizontal spaces
  • Target_String: Match literal text Target_String
  • \\h*,?: Match 0 or more horizontal spaces followed by an optional comma

Upvotes: 2

Omar Ayala
Omar Ayala

Reputation: 154

string.replace("\\s*,?\\s*Target_String\\s*,?\\s*", ""));

Upvotes: 0

Pavneet_Singh
Pavneet_Singh

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

Nowhere Man
Nowhere Man

Reputation: 19545

Try: string.replace(",\\s*Target_String\\s*", ""));

Demo

Upvotes: 0

Related Questions