簡體   English   中英

有人可以幫我將這個用C#編寫的正則表達式轉換為javascript嗎?

[英]Can someone help me to convert this regex expression written in C# to javascript?

我必須在文本框中為文本做一些模式匹配。 我在C#中的服務器的回發事件中這樣做。 我的正則表達式如下:

 public bool ValidatePassword(string temp)
    {
        bool isMatch = false;
        passwd = passwd.Trim();

        isMatch = Regex.IsMatch(temp,
                             @"^           # Start of string
                        (?=.*\p{Lu})      # Assert at least one uppercase letter
                        (?=.*\p{Ll})      # Assert at least one lowercase letter
                        (?=.*\d)          # Assert at least one digit
                        (?=.*[^\p{L}\d])  # Assert at least one other character
                        .{8,13}           # Match at least 8 characters and maximum of 13 characters
                        $                 # End of string",
                             RegexOptions.IgnorePatternWhitespace);


        return isMatch;
    }

我想將它移動到Javascript,以便我在客戶端進行匹配。 有人可以幫助我將此功能移動到Javascript嗎?

就像是:

function ValidatePassword(temp) {
  return /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[^a-zA-Z\d]).{8,13}$/.test(temp);
}

JavaScript正則表達式實現只理解拉丁字符的情況,它沒有實現國家字符語義,所以,遺憾的是,沒有辦法翻譯這個正則表達式,甚至沒有任何接近原點的表達式...

如果您正在將此作為學習練習,那么,或許,您可以查看正則表達式的Perl實現並獲得它的副本。 但如果您的問題更多地出現在實際領域,那么請考慮您的目標受眾以及他們可能輸入的語言,查找Unicode代碼點以查找其字符集中的小字母/大字母並相應地采取相應措施。 另請注意,許多非拉丁語言都沒有字母案例的概念。

或者,也許,考慮更嚴格的密碼規則。 :)

在Javascript中匹配大寫和小寫字母並不容易,因為它不支持\\p{…}字符類。 我建議你在正則表達式之外進行測試。 另外,“其他角色”很難定義,只是[^a-z0-9] ,還是沒有變形金剛等? 順便說一句,你寧可應該使用比更神秘的密碼更長的密碼。

function validatePassword(temp) {
    // temp = temp.trim() - is not supported in all browsers or needs to be shimmed
    //                      will be done in the regex

    if (temp.toUpperCase() == temp) // no lowercase char
        return false;
    if (temp.toLowerCase() == temp) // no uppercase char
        return false;

    return temp.test(/^\s*(?=.*\d).{8,13}\s*$/);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM