JavaScript regex gets all numbers, but excludes everything between brackets

I have a line:

123 df456 555 [ 789 ] [abc 1011 def ] [ ghi 1213] [jkl mno 1415 pqr] 161718 jkl 1920

I need to get only numbers that do not fit between square brackets [ ]. All the numbers given that I need to place inside The square brackets [ ] correct result should be:

[123] df456 [555] [ 789 ] [abc 1011 def ] [ ghi 1213] [jkl mno 1415 pqr] [161718] jkl [1920]

I tried to write a JavaScript regular expression like this: /(?!\[(.*?)\])((\s|^)(\d+?)(\s|$))/ig

but it seems wrong, it seems that a positive look has more priority than a negative result.

+4
source share
4 answers

Assuming square brackets are balanced and not nested, you can also use negative lookup to capture numbers outside [...]:

var str = '1232 [dfgdfgsdf 45] 1234 [ blabla 101112 ] 67890 [113141516 ] bla171819 212123';
var re = /\b\d+\b(?![^[]*\])/g;

var repl = str.replace(re, "[$&]");

console.log(repl);
//=> [1232] [dfgdfgsdf 45] [1234] [ blabla 101112 ] [67890] [113141516 ] bla171819 [212123]
Run codeHide result

, ] , [.

RegEx:

\b             # word boundary
\d+            # match 1 or more digits
\b             # word boundary
(?!            # negative lookahead start
   [^[]*       # match 0 or more of any character that is not literal "["
   \]          # match literal ]
)              # lookahead end

- RegEx

+2

[ ] , ( ):

/\[[^\][]*\]|\b(\d+)\b/g

regex .

:

  • \[[^\][]*\] - [, 0+, [ ], ]
  • | -
  • \b -
  • (\d+) - 1,
  • \b -
  • /g - ,

var regex = /\[[^\][]*\]|\b(\d+)\b/ig;
var str = '1234 [ blabla 101112 ] 67890 [113141516 ] bla171819 212123';
var res = [];
while ((m = regex.exec(str)) !== null) {
  if (m[1]) res.push(m[1]);
}
console.log(res);
Hide result
+1

, ... - :

var string = '1234 [ blabla 101112 ] 67890 [113141516 ] bla171819 212123';

string.replace(/\[.+?\]/g, '').match(/\b\d+\b/g);
  // => ["1234", "67890", "212123"]
+1

, :

var str = "1234 [ blabla 101112 ] 67890 [113141516 ] bla171819 212123",
 result = str.match(/\d+(?=\s*\[|$)/g);
console.log(result);
Hide result
\d+(?=\s*\[|$)

Regular expression visualization

Debuggex

+1

Source: https://habr.com/ru/post/1656009/


All Articles