2

If I have a string like the following that can have two possible values (although the value JB37 can be variable)

String One\r\nString Two\r\n
String One\r\nJB37\r\n

And I only want to capture the string if the value following String One\r\n does NOT equal String Two\r\n, how would I code that in Regex?

So normally without any condition, this is what I want: String One\r\n(.+?)\r\n

2
  • google negative lookahead. Commented Aug 28, 2018 at 14:52
  • Try ^String One\\r\\n(?!String Two)([^\\]+)\\r\\n$ here Commented Aug 28, 2018 at 14:53

1 Answer 1

1

With regex, you may resort to a negative lookahead:

String One\r\n(?!String Two(?:\r\n|$))(.*?)(?:\r\n|$)

See the regex demo

You may also use [^\r\n] instead of .:

String One\r\n(?!String Two(?:\r\n|$))([^\r\n]*)

If you use RegexOptions.Multiline, you will also be able to use

(?m)String One\r\n(?!String Two\r?$)(.*?)\r?$

See yet another demo.

Details

  • (?m) - a RegexOptions.Multiline option that makes ^ match start of a line and $ end of line positions
  • String One\r\n - String One text followed with a CRLF line ending
  • (?!String Two\r?$) - a negative lookahead that fails the match if immediately to the right of the current location, there is String Two at the end of the line
  • (.*?) - Capturing group 1: any zero or more chars other than line break chars, as few as possible, up to the leftmost occurrence of
  • \r?$ - an optional CR and end of the line (note that in a .NET regex, $ matches only in front of LF, not CR, in the multiline mode, thus, \r? is necessary).

C# demo:

var m = Regex.Match(s, @"(?m)String One\r\n(?!String Two\r?$)(.*?)\r?$");
if (m.Success) 
{
     Console.WriteLine(m.Groups[1].Value);
}

If CR can be missing, add ? after each \r in the pattern.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.