簡體   English   中英

正則表達式未按預期進行評估

[英]Regular Expression not evaluating as expected

我試圖評估下面的代碼,但它沒有返回預期的內容。 使用字符串“CityName !!!”進行測試 返回true而不是false。 我的表達式應該只允許一個字母和空格的字符串,任何長度,以字母開頭。

protected bool isValidCityName(string cityName)
    {
        Regex cityMatch = new Regex(@"^[a-zA-Z][a-zA-Z\s]+");

        return cityMatch.IsMatch(cityName);
    }

謝謝

您的模式只檢查字符串是否以該模式開頭 您需要包含一個結束錨( $ )以確保匹配后沒有尾隨字符:

Regex cityMatch = new Regex(@"^[a-zA-Z][a-zA-Z\s]+$");

此外,您可能需要考慮使用IgnoreCase選項:

Regex cityMatch = new Regex(@"^[a-z][a-z\s]+$", RegexOptions.IgnoreCase);

如果您需要應用程序支持其他語言/區域設置(例如魁北克),請使用Unicode類別

Regex cityMatch = new Regex(@"^\p{L}[\p{L}\s]+$");

嘗試在結尾添加$

Regex cityMatch = new Regex(@"^[a-zA-Z][a-zA-Z\s]+$");

現在,您的表達式只需要字符串以這些字符開頭 ^表示字符串的開頭, +表示一個或多個 $表示字符串的結尾

幾乎所有正則表達式解析器都是一樣的。

暫無
暫無

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

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