Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove underscore from string except from the link in string

I have a text paragraph which may contain some url links. I need to remove the underscores "_" only from that string.

But as I told text have url links and url links may also have underscores but their underscores should not be removed.

The links can be in any order i.e. there might be some text above or below those links, basically this is the email text content which would be sent in emails.

I was thinking to use some regex but that would remove the underscores from the links as well which I don't want. I was thinking to take out those links and then remove the underscores and then again add back the links in the text but as I told the links can be in different orders i.e. the text is dynamic content.

Any guidance would be appreciated and I will take it from there. Thanks.

like image 772
Manik Arora Avatar asked Sep 04 '26 07:09

Manik Arora


1 Answers

You can make use of a variable width negative look-behind (?<!\b(?:https?://\S*|www\.))_:

(?<!\b(?:https?://|www\.)\S*)_

See demo

This regex will match any _ that is not preceded with http:///https:///www. followed by any number of any characters other than whitespace (\S*).

C#:

var res = Regex.Replace(str, @"(?<!\b(?:https?://|www\.)\S*)_", string.Empty);
like image 155
Wiktor Stribiżew Avatar answered Sep 06 '26 21:09

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!