-2

My input is a string like the following-

some random text <http…any characters> more random text

or it could include https

some random text <https…any characters>  more random text

I want my output to replace anything "including" the angle brackets with nothing. So my output should be the following-

some random text more random text

I'm using C# to do this so here's an example of my code:

static string RemoveLinks(string source)
    {
        const string pattern = "Need Regex Pattern Here";

        return Regex.Replace(source, pattern, "");
    }

Can someone please help with a pattern match?

Kevin Moore
  • 361
  • 4
  • 14

2 Answers2

2

The other answer breaks if there are more than just one set of brackets. I would use this instead:

<[^>]+>

Essentially, the char class ensures that the match does not catch an ending >.

Depending on your needs, you may want to add some more to the regex:

<http[^>]+>

or, if you must ensure it's separated by spaces from the surrounding text:

(\s)<http[^>]+>(\s)

In that case, you would replace it with $1$2 to ensure that the surrounding spaces are preserved. Or, if you just want a normal space instead, you can just use the string " ". (Obviously.)


Important: I recommend using raw strings, like @"your regex with \backslashes", not regular strings.

Laurel
  • 5,965
  • 14
  • 31
  • 57
0

Go here to get all that info.

Probably something like:

string pattern = "\s<.*>\s";

Would be correct. You can do some easy testing using Notepad++ since it has regex options in its find & replace tool. That way you can do a more accurate test and make sure it's all working correctly.

kyle_engineer
  • 280
  • 1
  • 11