1

I have created the following Regular Expression in C# to extract tokens from a string in the format {token}. I developed the regex in C# and confirmed that it works.

// c#
var regex = new Regex(
    "\\{ (?>[^{}]+| \\{ (?<number>) | \\} (?<-number>) )*(?(number)(?!))\\}",
    RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | 
    RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);

var matches = regex.Matches("blah {token1} blah blah  blah {token2} blah");

The variable matches ends up containing two matches - "{token1}" and "{token2}".

I need to execute this in JavaScript, but I get a Syntax error in the expression when I try to execute the following line...

// JavaScript
var regex = new RegExp("\\{ (?>[^{}]+| \\{ (?<number>) | \\} (?<-number>) )*(?(number)(?!))\\}");

Is there anything obvious that I am doing wrong?
Am I trying to use RegEx features that are not supported in JavaScript?

3 Answers 3

4

If you want to match all occurences of "{something}" try:

\{[^\}]*\}

Or is there another condition that has to be met? like {token[0-9]}?

http://rubular.com/ can help with testing.

Sign up to request clarification or add additional context in comments.

1 Comment

No additional requirement. That does actually seem to work for me. The following line gives me the matches I need...text.match(/\{[^\}]*\}/g); It seems I was horribly overcomplicating it. I really struggle with the regex stuff. I have huge respect for anyone who has got their heads round it. Many thanks.
4

Independent subexpressions qualified with (?> ... ) aren't supported in Javascript regular expressions. The ? is actually evaluated as a quantifier.

3 Comments

This is browser-specific, some actually recognize a more or less extended kind of regular expression.
I figured it would be something like this. Thanks for the info. It sounds like it's back to the drawingboard.
Yes. Suppressing capturing using (?: ... ) does work for example.
2

The main point is that if you use C# (or Java) you use a string to write the regular expression. In such a string you need to escape all escaping characters again, which is why you need "\\{" to escape a "{". JavaScript however supports its own syntax of regular expression similar to Perl and PHP I think.

1 Comment

So there is more than one problem with this. Incorrectly escaping characters as well as using regex features that the engine doesn't support. I'm good!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.