Problem:

之前在專案中, 有測到一個疑似一個 .NET Framework Regex 的 bug?

例如使用 PATTERN = “\w”

\w表示任何一個字元與數字以及 '_' ,意同 [a-zA-Z0-9_]

輸入全形英數字及中文字可以通過在 Server side 的 Regular expression 檢查

但相同的 pattern 在 Javascript 的 Regular expression 是不會過的

最近找到答案了…

Root Cause:

    Server side RegExp uses a different regular expression engine than JavaScript.

Solution:

    You can get compatible behavior by using a RegexOptions.EcmaScript with your Regex.

    Regex regexp = new Regex("\\w", RegexOptions.ECMAScript);

    For more information:

    RegexOptions 列舉型別

    http://msdn.microsoft.com/zh-tw/library/system.text.regularexpressions.regexoptions.aspx

    ECMAScript vs. Canonical Matching Behavior

    http://msdn.microsoft.com/en-us/library/04ses44d(VS.71).aspx

Sample:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RegExpApp._Default" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
function testRegExp()
{
var email = document.getElementById("<%=txtEmail.ClientID %>").value;
var regexp = new RegExp("\\w");
if (email.match(regexp)) {
alert("Successful match");
} else {
alert("No match");
}
}
</script>


<script runat="server">
protected void btnNETRegExp_Click(object sender, EventArgs e)
{
Regex regexp;

if (chkECMAScript.Checked)
{
regexp = new Regex("\\w", RegexOptions.ECMAScript);
}
else
{
regexp = new Regex("\\w");
}

if(regexp.IsMatch(txtEmail.Text))
{
Response.Write("Successful match");
}
else{
Response.Write("No match");
}

}


</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="btnNETRegExp" runat="server" Text="NET RegExp" OnClick="btnNETRegExp_Click" />
&nbsp;&nbsp;&nbsp;
<asp:CheckBox ID="chkECMAScript" runat="server" />
<br />
<br />
<input id="btnJSRegExp" type="button" value="JavaScript RegExp" onclick="testRegExp();" /></div>
</form>
</body>
</html>

 

Hope this helps.

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 anISV 的頭像
    anISV

    慢步在雲端..

    anISV 發表在 痞客邦 留言(0) 人氣()