Regex exclude ":" and a whitespace if they exist

Viewed 53

So I have a regex here:

var text = new Regex(@"(?<=Paybacks).*", RegexOptions.IgnoreCase);

This looks for the line where it starts with Paybacks. Now it currently prints ": blah". The context sometimes can be "Paybacks" or "Paybacks:" or "Paybacks " or I don't know "Paybacks (with thousands of whitespaces). How can I modify this regex to be like.. after "Paybacks" ignore a colon and a whitespace (or whitespaces) that may or may not exist.

I've been playing with it in regex101 and this seems to be working, but is there a better way?

(?<=Volatility(:\s)).*
2 Answers

In these situations, you'd better use a regex with a capturing group:

var pattern = new Regex(@"Paybacks[\s:]*(.*)", RegexOptions.IgnoreCase);

Then, you can use

var output = Regex.Match(text, pattern)?.Groups[1].Value;

See the .NET regex demo:

enter image description here

See the C# demo:

var texts = new List<string> { "Paybacks: blah","Paybacks:blah","Paybacks blah"};
var pattern = new Regex(@"Paybacks[\s:]*(.*)", RegexOptions.IgnoreCase);
texts.ForEach(text => Console.WriteLine(pattern.Match(text)?.Groups[1].Value));

printing 3 blahs.

You might also match optional colons and whitspace chars in the lookbehind, and start matching the first chars being any non whitspace char other than :

(?<=Paybacks[:\s]*)[^\s:].*

The pattern matches:

  • (?<= Positive lookbehind, assert what is on the left is
    • Paybacks Match literally
    • [:\s]* Optionally match either : or a whitespace char using a character class
  • ) Close lookbehind
  • [^\s:].* Match a single non whitespace char other than : and the rest of the line

Regex demo | C# demo

var regex = new Regex(@"(?<=Paybacks[:\s]*)[^\s:].*", RegexOptions.IgnoreCase);
string[] strings = {"Paybacks: blah", "Paybacks blah", "Paybacks                  blah"};

foreach (String s in strings)
{
    Console.WriteLine(regex.Match(s)?.Value);
}

Output

blah
blah
blah

If the order should be a single optional colon and optional whitespace chars, you can make the colon optional and the quantifier for the whitespace chars 0 or more using :?\s*

(?<=Paybacks:?\s*)[^\s:].*

Regex demo

Related