C#中的RegEx无法正常工作

lar*_*ers 3 c# regex asp.net

我有个问题.

我希望允许用户在瑞典语键盘上编写您可以看到的所有内容(不使用字符映射或类似内容).这意味着所有英文字母数字字符和åäö.允许的非字母数字字符是§½!"@#£¤$%&{/()[]=}?+\´`^等等.

我的表达是:

[\wåäö§½!"@#£¤$%&/{()=}?\\\[\]+´`^¨~'*,;.:\-_<>|]
Run Code Online (Sandbox Code Playgroud)

在C#中它看起来像这样:

Regex allowedChars = new Regex("@[\\wåäö§½!\"@#£¤$%&/{()=}?\\\\[\\]+´`^¨~'*,;.:\\-_<>|]");
Run Code Online (Sandbox Code Playgroud)

我检查一下:

if (allowedChars.IsMatch(mTextBoxUserName.Text.Trim()))
Run Code Online (Sandbox Code Playgroud)

问题是,如果我将一个有缺陷的字符与一个允许的字符一起编写,那么if语句会认为它是匹配的.我想让它与整个单词相匹配.我尝试在表达式的末尾添加一个"+",但它从未匹配过......

有任何想法吗?

SLa*_*aks 6

你应该锚定正则表达式^[...]+$.


use*_*116 5

两件事情:

  1. 你的字符串错误地将@字符放在字符串内部而不是字符串之前.这可能是复制粘贴错误,或者可能不是.

    // put the @ outside the ""
    new Regex(@"[\wåäö§½!""@#£¤$%&/{()=}?\\[\]+´`^¨~'*,;.:\-_<>|]");
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您只检查其中一个允许的字符是否存在,而不仅仅是允许的字符.您可以使用锚定和重复来解决此问题:

    // anchor using ^ and $, use []+ to ensure the string is ONLY made
    // up from that character class. Also move the - to be the last symbol
    // to avoid inadvertent ranging
    new Regex(@"^[\wåäö§½!""@#£¤$%&/{()=}?\[\]+´`^¨~'*,;.:\\_<>|-]+$");
    
    Run Code Online (Sandbox Code Playgroud)