Jamil Ferdaus
Jamil Ferdaus

Reputation: 167

regex.replace #number;#

What would be the regex expression to find (PoundSomenumberSemiColonPound) (aka #Number;#)? I used this but not working

 string st = Regex.Replace(string1, @"(#([\d]);#)", string.Empty);

Upvotes: 1

Views: 2750

Answers (4)

Brad Christie
Brad Christie

Reputation: 101614

(\x23\d+\x3B\x32)

# and / are both used around patterns, thus the trouble. Try using the above (usually when I come in to trouble with specific characters I revert to their hex facsimile (asciitable.com has a good reference)

EDIT Forgot to group for replacement.

EDITv2 The below worked for me:

String string1 = "sdlfkjsld#132;#sdfsdfsdf#1;#sdfsdfsf#34d;#sdfs";
String string2 = System.Text.RegularExpressions.Regex.Replace(string1, @"(\x23\d+\x3B\x23)", String.Empty);
Console.WriteLine("from: {0}\r\n  to: {1}", string1, string2);;

Output:

from: sdlfkjsld#132;#sdfsdfsdf#1;#sdfsdfsf#34d;#sdfs
  to: sdlfkjsldsdfsdfsdfsdfsdfsf#34d;#sdfs
Press any key to continue . . .

Upvotes: 1

Brian Rasmussen
Brian Rasmussen

Reputation: 116461

You don't need a character class when using \d, and as SLaks points out you need + to match one or more digits. Also, since you're not capturing anything the parentheses are redundant too, so something like this should do it

string st = Regex.Replace(string1, @"#\d+;#", string.Empty);

Upvotes: 0

bdukes
bdukes

Reputation: 156005

You may need to escape the # symbols, they're usually interpreted as comment markers, in addition to @SLaks comment about using + to allow multiple digits

Upvotes: 0

SLaks
SLaks

Reputation: 887847

You're looking for #\d+;#.

  • \d matches a single numeric character
  • + matches one or more of the preceding character.

Upvotes: 4

Related Questions