I have regular expression which matches in .NET but not in Java. I consider the Java version to be correct, so I am wondering how I can duplicate this functionality in .NET.
This is the pattern:
([12AB]?)[: ]*(Mo|Mn|M|Tu|We|Wd|W|Th|Fr|F|Sa|Su)(\w*)[: ]*(\w*)[: ]*(\w*)
This is the test string:
D1:AM
Here's a working example: RegEx Fiddle
Click on Java to see the result from Java:

And the result from clicking on .NET:

There is no difference, except, again, that you are yet another victim of Java's misnamed .matches() method. Regex matching can happen anywhere in the input, if you want to match, say, only at the beginning of the input, you have to tell the regex engine explicitly.
If you look again at the images you pasted, you will see that .find() for Java returns true, same as .Match() for .NET. Java's .find() does real regex matching, and so does .NET's .Match().
Java is at fault here for misnaming .matches(), since it anchors the regex at both the beginning and end (side note: .lookingAt() anchors at the beginning only). If you want to replicate that behavior in .NET, anchor your regex:
^([12AB]?)[: ]*(Mo|Mn|M|Tu|We|Wd|W|Th|Fr|F|Sa|Su)(\w*)[: ]*(\w*)[: ]*(\w*)$
(but from looking at your screenshot, it looks like you used another regex than the one you quoted: neither D1:AM nor D1:PM are matched by the regex above)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With