I'm trying to match the first number of a comma separated list inside 2 bbcode tags. For instance, I want to match "10" in these 2 cases:
[productid]10,20,30[/productid] => 10
[productid]10[/productid] => 10
I'm novice in regex. I've been trying things like this with no luck:
\[productid\](.*)(?=,)\[\/productid\]
Any help will be appreciated! Thank you.
CodePudding user response:
Use this one
\[productid\](\d ?)(?=\D).*\[\/productid\]
\[productid\]
bbcode open tag(
Capturing group\d ?
Non-greedy number match
)
Close group(?=
Lookahead assertion - assert that the following regex matches\D
Match anything but numbers
)
Close lookahead.*
Match anything\[\/productid\]
bbcode close tag
See the preview
CodePudding user response:
The most straightforward solution without relying on fancy features like lookahead assertions is \[productid\](\d ).*?\[\/productid\]
. Explanation:
- Opening BBCode tag
- Greedily match the first number inside the tag
- Lazily match anything else (including other comma-separated numbers) up to the corresponding closing tag. The lazy matching is required for multiple inline tags such as
[productid]10[/productid] inline works too [productid]42,yay[/productid]
to work properly; Artyom's solution will fail for those, greedily consuming the entire second tag when parsing the first.