.NET Regex - Get string after match

Viewed 64

I am working with some strings that are usually following the next format:

word1 word2 word3 word4

My initial goal was to return the string's part coming after the second space and so to get:

word3 word4

I searched a bit how to do so and I only succeed to retrieve the first two words including the second space ("word1 word2 ") thanks to the next regex:

^([^\s]*\s[^\s]*)\s

Now to match my initial goal, I would like to find way to return the rest of the string that actually didn't match the given patter. Any idea ?

It's important to notify that I also have to handle the next cases:

"" -> ""
"word1" -> ""
"word1 word2" -> ""
"word1 word2 word3" -> "word3"
"word1 word2 word3 word4 wordX" -> "word3 word4 wordX"

Basically to return everything after the second spacing (if there is any obviously !). I also would like to avoid the Replace or any other methods.

I thank you all in advance for your response and wish you a great day ! Best regards,

3 Answers

You may rely on a variable length lookbehind in .NET regex:

(?<=^(?:\S+\s+){2}).+

See the .NET regex demo (\s replaced with a space since that is a multiline string demo, you may replace the space with [\s-[\r\n]] or [\p{Zs}\t] to only match horizontal whitespace chars).

Details

  • (?<=^(?:\S+\s+){2}) - the positive lookbehind that will match a location that is immediately preceded with 2 occurrences of 1+ non-whitespace chars followed with 1+ whitespace chars at the start of the string
  • .+ - 1+ chars other than a newline (if (?s) is added at the pattern start, . with match any chars).

No need for Regex. You can try this:

var inputString = "word1 word2 word3 word4";
string.Join(" ", inputString.Split(' ').ToList().Skip(2).ToList());

This one also matches

^(?:(\w+ ?)?(\w+ ?)?)(.*$)

DEMO

Related