Click here to Skip to main content
15,880,469 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have created a barcode validator, and some of the barcodes we get may be in a format such as (03) 15645 132156464
I would like to remove only spaces and brackets. I do not want to remove anything else, such as Barcode pending

Although I can probably use string.Replace, I want to give Regex a go.

What I have tried:

So far I have found I can do the following...
C#
string sampleBarcode = "(03) 15645 132156464";

// Remove spaces
sampleBarcode = Regex.Replace(sampleBarcode, @"\s+", "");

// Remove opening brackets
sampleBarcode = Regex.Replace(sampleBarcode, @"\(", "");

// Remove closing brackets
sampleBarcode = Regex.Replace(sampleBarcode, @"\)", "");

What I cannot figure out, is how to do this with just the one Regex statement.

Any help is appreciated.
Posted
Updated 27-Oct-22 22:40pm

Figured it out.

C#
sampleBarcode = Regex.Replace(sampleBarcode, @"\s+|\(+|\)+", "");
 
Share this answer
 
Your example as shown doesn;t work: it leaves ")" characters.
And a simpler version would be:
RegEx
[\s()]
which does it on a character-by-character basis.

If you are going to use Regexes, then get a copy of Expresso[^] - it's free, and it examines, tests, and generates Regular expressions.
 
Share this answer
 
Comments
Grant Mc 28-Oct-22 5:02am    
Your right, this works well.
Spent three hours looking for this, and the answer is soo simple.

Appreciate your assistance.
OriginalGriff 28-Oct-22 5:21am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900