Get an actual substring with Regex in c#

Viewed 35

I have this pattern

@"($\w+)"

And it will successfuly catch for example $substring inside long text $substring the rest of the text.

But it will fail in certain scenarios, for example some string $sub.string the rest of string will only return $sub

What can I do to get an actual full substring from the string?

1 Answers

You can use

\$\S+

See the .NET regex demo.

NOTE: If you want to get rid of any trailing punctuation (other than _) you may add \b at the end, \$\S+\b.

Details:

  • \$ - a $ char (needs escaping since $ is a special metacharacter asserting end of string position)
  • \S+ - any one or more non-whitespace chars.

In C#, you can use

var output = Regex.Matches(text, @"\$\S+").Cast<Match>().Select(x => x.Value).ToList();
Related