简体   繁体   中英

Regular Expression: 0-9 A-Z a-z or any of these '!#$%&'*+-/=?^_`{|}~

I need to regex string myString to only have:

  • 0-9
  • AZ or az
  • any of these characters '!#$%&'*+-/=?^_`{|}~.

This is my code line:

new Regex("[a-zA-Z0-9]").IsMatch(myString);

So far I have [a-zA-Z0-9] and this works fine for the first two listitems. Currently tearing my hair out (and it's so nice I want to keep it) over metacharacters and getting nowhere.

Any help would be greatly appreciated. Thanks. Dave

嗨那里如果您只想要字符串中列出的字符,那么它非常简单。但您需要匹配开头的行尾

new Regex("^[a-zA-Z0-9'!#$%&'*+/=?^_`{|}~.-]*$").IsMatch(myString);
"[a-zA-Z0-9'!#$%&'*+/=?^_`{|}~.-]"

检查(“ - ”)减号是[]序列中的最后一个字符

Meta characters are fine between brackets, as long as you escape the significant ones. Moreover the dash MUST be the last one of your sequence.

new Regex("[a-zA-Z0-9'!#$%&'*+/=?^_`{|}~-]").IsMatch(myString);

尝试:

var re = "[a-zA-Z0-9" +  Regex.Escape("'!#$%&'*+-/=?^_`{|}~.") + "]";

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