正则表达式从短代码标记中解析键值对

时间:2014-03-20 00:21:46

标签: javascript regex

我有一个javascript正则表达式来解析短代码及其内容,但现在我尝试修改它以从标记的属性中解析出一个键/值对。

示例:

[shortcode name="test"]
the shortcode conents
[/shortcode]

我想收到以下比赛:

  • 标记名称(shortcode
  • 标记属性,不带引号(name=test
  • 标记内容(the shortcode contents

我的正则表达式目前为:/\[([^\]]*?)\]([\s\S]*?)\[\/\1\]/ig

将采取以下措施:

[shortcode]
the shortcode contents
[/shortcode]

并返回

  • shortcode
  • the shortcode contents

所以现在我正在尝试获取属性,我们也可以假设密钥name是一致的,所以我们不会期望任何其他键值对,只需name="something"就可以了

1 个答案:

答案 0 :(得分:1)

我会在两个正则表达式fiddle

中执行此操作
var split_bits = /\[([^\]]+)]([^\[]+)\[\/([^\]]+)]/ig,
    bits = split_bits.exec( shortcode );

var split_arguments = /([a-zA-Z]+)="([^"]+)+"/gi,
    arguments = split_arguments.exec( bits[1] );

第一个获取短代码标签名称&内容。然后将短代码的第一部分传递给定位参数的第二个正则表达式。

注意:仍然在解析多个参数。