Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx 'matches' different between Java and .NET

Tags:

java

c#

.net

regex

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: Java Regex Result

And the result from clicking on .NET: .NET Regex Result

like image 852
Marcus Avatar asked Apr 20 '26 11:04

Marcus


1 Answers

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)

like image 64
fge Avatar answered Apr 22 '26 01:04

fge