简体   繁体   中英

RegEx in C# does not work as supposed

I have a problem.

I want a user to be allowed to write everything you can SEE on a Swedish keyboard (not using a character map or similar). This means all English alphanumeric characters and åäö . The non-alphanumeric characters which is allowed is §½!"@#£¤$%&{/()[]=}?+\\´`^ and so on.

My expression is:

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

In C# it looks like this:

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

I check it with:

if (allowedChars.IsMatch(mTextBoxUserName.Text.Trim()))

The problem is that if i write a faulty character together with an allowed character the if statement think its a match. I want it to match it for the entire word. I tried adding a "+" at the end of the expression but then it never matched...

Any ideas?

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

Two things:

  1. Your string erroneously has the @ character inside rather than before the string. This may have been a copy paste error, or it might not have been.

     // put the @ outside the "" new Regex(@"[\\wåäö§½!""@#£¤$%&/{()=}?\\\\[\\]+´`^¨~'*,;.:\\-_<>|]"); 
  2. You're only checking that one of the allowed characters is present, rather than ONLY the allowed characters. You can use anchoring and repetition to solve this problem:

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

Remove the @ from the start of your string - your regex to your C# equivalent is incorrect.

The @ prefix comes outside of the quotes @"anyStringHere" and it means the \\ character is treated as a literal rather than an escape character in the string.

Also, I presume you wish to match a string that is composed of only allowed characters, if so you should anchor your regex: ^[regexHere]+$

You can put ^ immediately following the first [. That means it will match any character that is NOT in the set. Then IsMatch will return True for strings that contain any character that is not in the list, so it will return False for valid strings.

Instead of checking if a string is valid, you'll be checking if the string is invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM