简体   繁体   中英

regex for javascript regular expressions

I need to parse some JavaScript code in C# and find the regular expressions in that.

When the regular expressions are created using RegExp, I am able to find. (Since the expression is enclosed in quotes.) When it comes to inline definition, something like:

var x = /as\/df/;

I am facing difficulty in matching the pattern. I need to start at a / , exclude all chars until a / is found but should ignore \\/ .

I may not relay on the end of statement ( ; ) because of Automatic Semicolon Insertion or the regex may be part of other statement, something like:

foo(/xxx/); //assume function takes regex param

If I am right, a line break is not allowed within the inline regex in JavaScript to save my day. However, there the following is allowed:

var a=/regex1def/;var b=/regex2def/;
foo(/xxx/,/yyy/)

I need regular expression someting like /.*/ that captures right data.

You cannot reliably parse programming languages with regular expressions only. Especially Javascript, because its grammar is quite ambiguous. Consider:

a = a /b/ 1
foo = /*bar*/ + 1
a /= 5 //.*/hi

This code is valid Javascript, but none of /.../ 's here are regular expressions.

In case you know what you're doing ;), an expression for matching escaped strings is "delimiter, (something escaped or not delimiter), delimiter":

 delim ( \\. | [^delim] ) * delim

where delim is / in your case.

How about this:

Regex regexObj = new Regex(@"/(?:\\/|[^/])*/");

Explanation:

/       # Match /
(?:     # Non-capturing group:
 \\     # Either match \
 /      # followed by /
|       # or
 [^/]   # match any character except /
)*      # Repeat any number of times
 /      # Match /

After several trials with RegexHero, this seems working. /.*?[^\\\\]/ . But not sure if I am missing any corner case.

I think that this may help you var patt=/pattern/modifiers;

•pattern specifies the pattern of an expression •modifiers specify if a search should be global, case-sensitive, etc.

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