0

I'm trying to build a regular expression that captures anything between square brackets like the following numbers.

[phone]010101[/phone] [phone]434343[/phone] [phone]3443434[/phone]

so the matches should be 010101, 434343, 3443434

I built cow([\s\S]*?)milk to experiment, and this seems to capture multiple matches and works fine with multiple lines, achieving what I exactly need.

However when I attempted to build the actual regex using this: \[phone\]([\s\S]*?)\[\/phone\] , it would only capture the first single match.

What could be wrong with my expression?

Sami
  • 63
  • 4
  • What are you trying to capture? For example in `[phone]010101[/phone]` what is your expected output? `010101` or `phone` & `/phone`? – moys Feb 25 '20 at 15:25
  • There's a problem with your input string. Can you see it? (one of the brackets is turned the wrong way). – Robert Harvey Feb 25 '20 at 15:25
  • If you fix the problem with your input string, your regex works. https://regex101.com/r/z7eJMD/1 – Robert Harvey Feb 25 '20 at 15:26
  • Robert, this seems to be a python version, does this also work on the JavaScript version for you? and yes I fixed the typo. – Sami Feb 25 '20 at 15:30
  • Sorry I was missing the global & multi-line flags. Thank you guys. – Sami Feb 25 '20 at 15:33

2 Answers2

0

Another approach. This will capture the numbers as you intend.

\](.*)\[

RegexDemo

moys
  • 7,747
  • 2
  • 11
  • 42
0

The regex is correct but global and multi-line flags are missing. In JavaScript, with g (global) and m (multiline) flags added to regex, intended matches can be found.

str=`[phone]010101[/phone] [phone]434343[/phone]
[phone]3443434[/phone]`;
reg = /\[phone\]([\s\S]*?)\[\/phone\]/gm;
[...str.matchAll(reg)].map(x=> x[1]); //["010101", "434343", "3443434"]