Krishna Sarma
Krishna Sarma

Reputation: 1860

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.

Upvotes: 0

Views: 185

Answers (4)

kaushik0033
kaushik0033

Reputation: 677

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.

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

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 /

Upvotes: 0

georg
georg

Reputation: 214949

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.

Upvotes: 3

Krishna Sarma
Krishna Sarma

Reputation: 1860

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

Upvotes: 0

Related Questions