简体   繁体   中英

How to determine whether a string has regex metacharacters? (C#)

Does the System.Text.RegularExpressions namespace offer me anything to discover whether an input string has ("abc[0-9]" or "^aeiou$") or has not ("abc123") metacharacters? Or do I have to check manually for non-escaped characters in a certain list?

You have at least three options:

  1. Use Regex.Escape and compare the result:

     private static bool ContainsMetaCharacters(string s) { if (String.IsNullOrEmpty(s)) { return false; } string escaped = Regex.Escape(s); return !escaped.Equals(s, StringComparison.Ordinal); } 
  2. Apply Regex.Escape to each character to see if the escaped value is different:

     private static bool ContainsMetaCharacters(string s) { if (String.IsNullOrEmpty(s)) { return false; } for (int i = 0; i < s.Length; i++) { if (Regex.Escape(s.Substring(i,1))[0] != s[i]) { return true; } } return false; } 
  3. Create your own based on the fact that the metachars shouldn't change:

     private static readonly char[] _MetaChars = new char[] { '\\t', '\\n', '\\f', '\\r', ' ', '#', '$', '(', ')', '*', '+', '.', '?', '[', '\\\\', '^', '{', '|' }; private static bool ContainsMetaCharacters(string s) { if(String.IsNullOrEmpty(s)) { return false; } return s.IndexOfAny(_MetaChars) >= 0; } 

The third approach offers more control depending on the RegexOptions you use in your Regex. For example, if you'll never use RegexOptions.IgnorePatternWhitespace, you can remove space as a metachar.

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