C# 和 JavaScript 正则表达式之间的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3982608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Differences between C# and JavaScript Regular Expressions?
提问by Michael Stum
Are C# and JavaScript Regular Expressions different?
C# 和 JavaScript 正则表达式不同吗?
Is there a list of these differences?
是否有这些差异的列表?
回答by Francis Norton
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.
我们正在使用“[AZ-[QVX]]”语法测试“一些但不是全部”字符类,例如“A 到 Z 但不是 Q、V 或 X”。不知道我们在哪里找到它,不知道它是否被记录在案,但它可以在 .Net 中使用。
For example, in Powershell, using the .Net regex class,
例如,在 Powershell 中,使用 .Net regex 类,
[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.
返回真。在 JavaScript 中测试相同的输入和模式,它返回 false,但在 JavaScript 中针对“^[AZ]$”测试“K”,它返回 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.
您可以使用更正统的负前瞻方法来表达“A 到 Z 但不是 Q、V 或 X”,例如“^(?![QVX])[AZ]$”,这将在 Powershell 和(现代) 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.
鉴于 Ben Atkin 上面关于 IE6 和 IE7 不支持前瞻的观点,以万无一失(或 IE7 证明)的方式做到这一点的唯一方法可能是扩展表达式,例如“[AZ-[QVX] " -> "ABCDEFGHIJKLMNOPRSTUWYZ"。哎哟。
回答by Benjamin Atkin
First, some resources:
首先,一些资源:
- Mozilla Development Center JavaScript Guide: Regular Expressions
- .NET Framework Regular Expressions- see the links at the bottom of the page
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.
- IE6 和 IE7 不支持 Lookahead。(
x(?=y)在 MDC 指南中搜索示例。) - JavaScript 不支持命名的捕获组。例子:
(?<foo>) - JavaScript 支持的元字符列表要短得多。

