Determine if a regular expression is just a literal match

Using the .NET Regex class, is there an easy way to check if a regular expression is a literal match without special characters (other than escaped special characters)?

Looking for something like this

var literalRegex = new Regex(@"\(foo\)");
var fancyRegex = new Regex("foo.*");
Console.WriteLine(IsPlainLiteral(literalRegex)); // True
Console.WriteLine(IsPlainLiteral(fancyRegex)); // False
+4
source share
2 answers

I suggest this pattern that matches all "literal patterns" (* understand well-formed patterns where all characters are literals or escaped with special characters or backslashes are ignored)

in the shorthand line:

\A
[^[\\|{.?*+^$()]*    # characters that aren't one of the twelve special characters
(?>
    (?: # exceptions:
        # - the opening curly bracket that is not the start of a quantifier
        {+ (?! [0-9]+ (?:,[0-9]*)? } ) 
      |
        # - the backslash if it escapes a character:
            # - that is one of the twelve special characters
            # - or produces an ignored escape sequence
        \\ [^\p{L}\p{N}]
    )
    [^[\\|{.?*+^$()]*
)*
\z

Note: this template is for .net syntax.

2: IgnorePatternWhitespace # , , : [^[\\|{.?*+^$()#\s]

+2

? , .

, , . , Regex , RegexTree.

, , :

1 node node node?

- , #, AST.

0
source

All Articles