I am trying to extract function notation from a string in javascript (so I can't use lookbehind), here are some examples:
Right now I am using
/\b[a-z]\([^x]/g
because I don't want to match when it is a string of letters (such as sqrt) only when there is a single letter then a parentheses. The problem I am having is with the last one in the list (nested functions). ( is not part of the \\b catches so it doesn't match.
My current plan is to add a space after every ( using something like
input = input.replace(/\([^\s]/g, '( ');
Which splits the nested function so that \\b comes into play [becomes f( g( 3))] but before I started messing with the input string, I thought I would ask here if there was a better way to do it. Obviously regex is not something I am super strong with but I am trying to learn so an explanation with the answer would be appreciated (though I will take any pointers that I can google myself too! I am not entirely sure of what to search for here.)
The point here is that [^x]
is a negated character class that still matches , consumes the symbol after (
and it prevents overlapping matches. To make a check that the next character is not x
, use a lookahead:
\b[a-z]\((?!x)
^^^^^
See regex demo
Perhaps, you want to fail a match only if a x
is the only letter inside f()
or g()
:
\b[a-z]\((?!x\))
From Regular-expressions.info :
is indispensable if you want to match something not followed by something else. 是必不可少的。 When explaining [character classes][4], . 。 The negative lookahead construct is the pair of parentheses, with the opening parenthesis followed by a question mark and an exclamation point .
I think you just have to remove [^x]:
"f(g(2))".match(/\b[a-z]\(/g)
// ["f(", "g("]
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.