Reputation: 19641
What is the problem with my code
var str = "[356] Hello World";
var patt = new RegExp("(?!\[)\d+(?<!\])","");
var result = patt.exec(str);
Result Should Be = 356
Upvotes: 2
Views: 168
Reputation: 30695
In addition to what others have pointed out, you have the wrong syntax for lookarounds.
(?!regex)
is a negative lookahead, but you're using it as a positive lookbehind.(?<!regex)
is a negative lookbehind, but you're using it as a positive lookahead.Since lookbehinds aren't supported in JS, Thai's and lonesomeday's answers are the way to go. In a language that did support them, you'd want this:
/(?<=\[)\d+(?=\])/
Upvotes: 1
Reputation: 11354
Lookbehinds are not supported in JavaScript.
You can instead try using capturing subpatterns.
var str = "[356] Hello World";
var match = str.match(/\[(\d+)\]/);
var result = match ? match[1] : null;
Upvotes: 1
Reputation: 237817
The problem is that you can't do negative lookbehinds in Javascript.
Something like this should work:
var str = '[356] Hello World',
patt = /\[(\d+)\]/,
result = patt.exec(str)[1];
This creates a matching group and selects the match with [1]
.
Upvotes: 2