我正在尝试编写一个需要返回每个标签名称、属性名称和属性值的正则表达式
代码示例如下
Hello, My name is Jack, This is my selfie:
[img id='4' src="imageurl"]
Below is the quick-link to my profile
[profile username='jackisbest']
我需要获取包含在 [ ] 中的任何文本
我还需要 javascript 正则表达式来解析它们并以这种方式匹配它们
> Match 1: img
> Match 2: id='4'
Group 1: id
Group 2: 4
> Match 3: src="imageurl"
Group 1: src
Group 2: imageurl
这是我正在使用的正则表达式,但它只能匹配属性和值
(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']
谢谢!!
最佳答案
你可以使用
/\[([a-zA-Z]\w*)|([^=\s]+)=["'](.*?)["']/g
参见 regex demo . 详细信息:
\[([a-zA-Z]\w*)
-[
字符,然后是一个字母,后跟零个或多个单词字符(字母、数字, 下划线)|
或([^=\s]+)
- 除了=
和空格之外的一个或多个字符=
-=
字符["'](.*?)["']
-"
或'
,然后任意零个或多个字符尽可能(捕获到第 3 组),然后是"
或'
字符。
关于javascript - 如何在正则表达式中获取 "tag name"、 "attribute name"、 "attribute value"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71059594/