3

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

Marcus
  • 9,011
  • 10
  • 45
  • 65
  • 3
    Being on a business network, I can't see the crux of your problem, because, images on a frequently blocked source. This is a potential problem for both of us, I'm not just sharing this for others to laugh at my misfortune. – Grant Thomas Jan 11 '13 at 16:19
  • Java apparently does [not support conditional expressions](http://stackoverflow.com/questions/14030146). – Paul Ruane Jan 11 '13 at 16:24
  • Thanks Grant, added some text info! – Marcus Jan 11 '13 at 16:25
  • @PaulRuane there are no conditionals in the regex – fge Jan 11 '13 at 16:25
  • Your test string will not match with either engine (the `(Mo|...)` alternation cannot be satisfied), are you absolutely sure this is the actual test string you used for the screenshots above? – fge Jan 11 '13 at 16:32

1 Answers1

7

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)

fge
  • 119,121
  • 33
  • 254
  • 329
  • Thanks, I thought that was the case but another Test Case I had was failing and I read the wrong conclusions from it. – Marcus Jan 11 '13 at 16:34
  • The regex does 'match' - check the RegEx Fiddle link on the Java version. – Marcus Jan 11 '13 at 16:41
  • Look at the Java table, it outputs the result for three methods: `matches()`, `lookingAt()` and `find()`. .NET's `Match()` is equivalent to Java's `find()`. – fge Jan 11 '13 at 16:43