user2615607
user2615607

Reputation: 25

Match up everything before STRING or STRING

I've searched for hours and already tried tons of different patterns - there's a simple thing I wan't to achive with regex, but somehow it just won't do as I want:

Possible Strings

String1

This is some text \0"§%lfsdrlsrblabla\0\0\0}dfglpdfgl

String2

This is some text

String3

This is some text \0

Desired Match/Result

This is some text

I simply want to match everything - until and except the \0 - resulting in only 1 Match. (everything before the \0)
Important for my case is, that it will match everytime, even when the \0 is not given.

Thanks for your help!

Upvotes: 2

Views: 126

Answers (2)

FrankieTheKneeMan
FrankieTheKneeMan

Reputation: 6800

I like

@"^((?!\\0).)*"

Because it's very easy to implement with any arbitrary string. The basic trick is the negative lookahead, which asserts that the string starting at this point doesn't match the regular expression inside. We follow this with a wildcard to mean "Literally any character not at the start of my string. If your string should change, this is an easy update - just

@"^((?!--STRING--).)*)"

As long as you properly escape that string. Heck, with this pattern, you're merely a regex_escape function from generating any delimiter string.

Bonus: using * instead of + will return a blank string as a valid match when your string starts with your delimiter.

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can try with this pattern:

@"^(?:[^\\]+|\\(?!0))+"

In other words: all characters except backslashes or backslashes not followed by 0

Upvotes: 2

Related Questions