Regex to match everything except a list of characters

我与影子孤独终老i 提交于 2021-02-16 08:59:09

问题


I want to match a line containing everything except the specified characters [I|V|X|M|C|D|L].

new Regex(@"^(.*) is (?![I|V|X|M|C|D|L].*)$")

should match everything except the characters mentioned in the OR list.

Should match -

name is a

Should not match -

edition is I

回答1:


Try this pattern:

^[^IVXMCDL]*$

This will match the start of the string, followed by zero or more characters other than those specified in the character class, followed by the end of the string. In other words, it will not match any a string which contains those characters.

Also note that depending on how you're using it, you could probably use a simpler pattern like this:

[IVXMCDL]

And reject any string which matches the pattern.




回答2:


You don't need | in this case, just use ^[^IVXMCDL]*$

^[^IVXMCDL]*$

Regular expression visualization

Debuggex Demo




回答3:


 private  bool IsValid(String input)
        {
            bool isValid = false;
            // Here we call Regex.Match.
            Match match = Regex.Match(input, @"^[^IVXMCDL]*$");

            // Here we check the Match instance.
            if (match.Success)
            {
               isValid = true;
            }
            else
            {
                isValid = false;
            }

          return isValid;
        }


来源:https://stackoverflow.com/questions/19806835/regex-to-match-everything-except-a-list-of-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!