Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my RegEx get two different results depending on platform?

Tags:

c#

.net

regex

I have a RegEx pattern:

@"((?(?!\.\d)\D)*)(\d*\.\d+|\d+)*((?(?<=\d).*))"

designed to break a string into 3 parts. If i have the strings

"asdf1234asdf"
"asdf .1234asdf"
"asdf. .1234asdf"
"asdf 12.34asdf"
"asdf123.4 asdf"
"asdf.1234asdf"

I need:

1. "asdf"     2. "1234"    3. "asdf"
1. "asdf "    2. ".1234"   3. "asdf"
1. "asdf. "   2. ".1234"   3. "asdf"
1. "asdf "    2. "12.34"   3. "asdf"
1. "asdf"     2. "123.4"   3. " asdf"
1. "asdf"     2. ".1234"   3. "asdf"

But depending on the platform i use, the results change.

Regex101.com gives me the results i need

though in Regexstorm.com i have to modify the if statement in the Regex to a non-capturing group for it to work

I.e.: I need to change it from

@"((?(?!\.\d)\D)*)(\d*\.\d+|\d+)*((?(?<=\d).*))"

to

@"((?:(?!\.\d)\D)*)(\d*\.\d+|\d+)*((?(?<=\d).*))"

to get it to work in .NET

So why do i need to get rid of the 'if' block? does .NET not support if blocks?

like image 482
maksymiuk Avatar asked Nov 14 '25 14:11

maksymiuk


1 Answers

RegEx is more similar to English than it is to C#. It's a language used to define patterns which will find matches within strings. Every language needs to implement their regular expression engine and therefore there are differences between most, while the concepts stay mostly the same. Usually, the more complicated the expression the more likely it isn't cross-platform compatible. That's why everyone will ask SO users what programming language they use when a vague RegEx question is asked.

This is why tools like RegEx101 need to have multiple "flavors" for testing an expression thoroughly. You'll also notice the "Quick Reference" content (cheat sheet containing tokens, quantifiers, etc.) changes as you change between engines.

Wikipedia: Comparison of regular expression engines.

like image 185
Sam Avatar answered Nov 17 '25 08:11

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!