themaestro
themaestro

Reputation: 14256

Replace Pattern with ""

I'm trying to write a regex that will take a string of the form:

<123>, ;<123>:::,<123>

where 123 is some number and in between the numbers is some punctuation.

I need a regex that will replace all the punctuation between the number fields with "".

I tried this:

Regex.Replace(s, ">.*<", "");

But had no luck. What regex would accomplish this?

Edit: My original regex was a bit misleading, sorry! As the commenters said, I'm looking for <123><123><123>

Upvotes: 0

Views: 517

Answers (4)

drf
drf

Reputation: 8709

Both of these should work:

Regex.Replace(s, @"(\>|^).*?($|\<(?=\d{3}\>))", "$1$2");

or

String.Concat(Regex.Matches(s, @"\<\d{3}\>")
            .OfType<Match>().Select(a => a.Groups[0]));

Upvotes: 1

David A Tarris
David A Tarris

Reputation: 81

Not sure about the exact C# syntax either, but if your string is guaranteed not to have numbers outside those angle brackets, then you should be able to get away with this:

Regex.Replace(s, "[^\d<>]*", "");

So remove anything that isn't a number or "<" or ">". If you also want to remove the angle brackets it's even simpler:

Regex.Replace(s, "[^\d]*", "");

Upvotes: 2

hakan
hakan

Reputation: 3544

you should use brackets as suggested. but i didnt get what exactly you wanted to replace.

string s = "<123>, ;<123>:::,<123>";

s = (new Regex("[<>:, ;]")).Replace(s, "\"");

final string will be;

"123"""""123""""""123"

Upvotes: 0

Mat
Mat

Reputation: 206909

You need to make the .* part non-greedy, otherwise it will pick up everything between the first > and the last < in your string. Try something like:

Regex.Replace(s, ">.*?<", "");

This will erase the > and < chars also. If you want to preserve those:

Regex.Replace(s, ">.*?<", "><");

Upvotes: 2

Related Questions