简体   繁体   English

在正则表达式中获取组的多个匹配项

[英]Get multiple matches of a group in regular expression

I am trying to get attributes from a BBCode using regular expression Lets say I have those strings: 我正在尝试使用正则表达式从BBCode获取属性。可以说我有那些字符串:

[icons a="1" b='2' c="3"]
[icons d="4" e='5' f="6"]

I need using a regular expression to get matches like this: 我需要使用正则表达式来获取匹配项,例如:

[
    {'a', '1', 'b', '2', 'c', '3'},
    {'d', '4', 'e', '5', 'f', '6'}
]

I figured this regular expression: 我想出了这个正则表达式:

\[icons[\w\s](?:(\w*)\=["|']([^"|']*))+.*?\]

But it only matches: 但这仅匹配:

[
    {'a', '1'},
    {'d', '4'}
]

How I can match all the attributes? 如何匹配所有属性?

Also, just to make it more bullet proof, is there a way to match only the quote it found? 另外,只是为了使其更防弹,是否有办法只匹配找到的报价?

[icons a="1"] // GOOD
[icons a="1'] // BAD - But still a match

Regex101 Regex101

I think the best way is to keep it simple: 我认为最好的方法就是保持简单:

Use one regex to match all the [icons...] : 使用一个正则表达式匹配所有的[icons...]

\[icons\b[^\[\]]*\]

and a second regex to be used iteratively on each of this regex' matches: 第二个正则表达式将在此正则表达式的每个匹配项上迭代使用:

(\w+)=(['"])((?:(?!\2).)*)\2

Note that the first and third group will contain your desired values, the second group contains the quote. 请注意,第一和第三组将包含您想要的值,第二组将包含引号。

您必须使用它,这可能会帮助您

\[icons\s(\w)[=]["|'](\d)["|']\s(\w)[=]["|'](\d)["|']\s(\w)[=]["|'](\d)["|']\]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM