admin管理员组文章数量:1391977
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?
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
Reset to default 4If 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./ can help with testing.
Independent subexpressions qualified with (?> ... )
aren't supported in Javascript regular expressions. The ?
is actually evaluated as a quantifier.
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.
本文标签: JavaScript RegEx Syntax ErrorStack Overflow
版权声明:本文标题:JavaScript RegEx Syntax Error - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744774097a2624519.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论