简体   繁体   中英

What Regular Expression Can I Use To Find Simple Regular Expressions

If I have a string, which is the source of a regular expression:

"For example, I have (.*) string with (\.d+) special bits (but this is just an aside)."

Is there a way to extract the special parts of the regular expression?

In particular, I'm interested in the parts that will give back values when I call string.match(expr);

Regex can be complicated, but if you do a global regex with ([\\.\\\\]([*az])\\+?) , it will capture your individual fields without including the parenthesis per your request. Demo code as put in this fiddle is below as well.

var testString = 'For example, I have (.*) string with (.d+) special bits (but this is just an aside). (\\w+)';
var regex = /([\.\\]([*a-z])\+?)/gi;

var matches_array = testString.match(regex);

//Outputs the following: [".*", ".d+", "\w+"]

Regular expressions are not powerful enough to recognize the language of matching parentheses. (The formal proof uses the equivalence of regular expressions and finite state machines and the fact that there are infinitely many levels of nesting possible.) Thus, matching the first ) after each ( would make (\\d+(\\.d+)?) return (\\d+(\\.d+) and matching the last ) after each ( would make (\\w+) (\\w+) match the entire string.

The correct way to do this is with recursion (which mathematical regular expressions do not allow, but actual implementations such as PCRE do). You can also get a simple expression for non-nested parentheses. Just be careful to parse escape characters: to be fully robust, \\( and \\\\\\( are special, but \\\\( is not.

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