27

Are C# and JavaScript Regular Expressions different?

Is there a list of these differences?

2 Answers 2

6

Here's a difference we bumped into that I haven't seen documented anywhere, so I'll publish it, and the solution, here in the hope that it will help someone.

We were testing "some but not all" character classes, such as "A to Z but not Q, V or X", using "[A-Z-[QVX]]" syntax. Don't know where we found it, don't know if it's documented, but it works in .Net.

For example, in Powershell, using the .Net regex class,

[regex]::ismatch("K", "^[A-Z-[QVX]]$") 

returns true. Test the same input and pattern in JavaScript and it returns false, but test "K" against "^[A-Z]$" in JavaScript and it returns true.

You can use the more orthodox approach of negative lookahead to express "A to Z but not Q, V or X", eg "^(?![QVX])[A-Z]$", which will work in both Powershell and (modern) JavaScript.

Given Ben Atkin's point above about IE6 and IE7 not supporting lookahead, it may be that the only way to do this in a fool-proof (or IE7-proof) way is to expand the expression out, eg "[A-Z-[QVX]" -> "ABCDEFGHIJKLMNOPRSTUWYZ". Ouch.

Sign up to request clarification or add additional context in comments.

1 Comment

well [A-PR-UWYZ] would be enough, no?
3

First, some resources:

Here are a few differences:

  • Lookahead is not supported in IE6 and IE7. (Search for x(?=y) in the MDC guide for for examples.)
  • JavaScript doesn't support named capture groups. Example: (?<foo>)
  • The list of metacharacters supported by JavaScript is much shorter.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.