【问题标题】:Help with regexp to extract values from inside brackets帮助正则表达式从括号内提取值
【发布时间】:2010-11-14 04:18:31
【问题描述】:

我想要一个正则表达式来提取以下内容。我有一个正则表达式来验证它(我把它拼凑在一起,所以它可能不是最好或最有效的)。

some.text_here:[12,34],[56,78]

冒号前的部分可以包含句点或下划线。冒号后括号内的数字是坐标[x1,y1],[x2,y2]...我只需要这里的数字。

这是我使用的正则表达式验证器(用于 javascript):

^[\w\d\-\_\.]*:(\[\d+,\d+],\[\d+,\d+])

我对正则表达式还很陌生,但我不知道如何提取值以便获取

name = "some.text_here"
x1 = 12
y1 = 34
x2 = 56
y2 = 78

感谢您的帮助!

【问题讨论】:

  • 仅供参考,您的正则表达式中的[\w\d\-\_\.][\w.-] 相同,因为(1)\w 匹配数字和下划线以及字母,(2). 在一个字符类,并且 (3) - 如果它是列出的第一个或最后一个字符,则没有特殊含义。
  • 感谢您的澄清:)

标签: javascript regex parsing


【解决方案1】:

可以使用字符串的match方法:

var input = "some.text_here:[12,34],[56,78]";

var matches = input.match(/(.*):\[(\d+),(\d+)\],\[(\d+),(\d+)\]/);

var output = {
  name: matches[1],
  x1: matches[2],
  y1: matches[3],
  x2: matches[4],
  y2: matches[5]
}

// Object name=some.text_here x1=12 y1=34 x2=56 y2=78

【讨论】:

    【解决方案2】:

    试试这个正则表达式:

    /^([\w\d-_.]*):\[(\d+),(\d+)],\[(\d+),(\d+)]/
    
    var str = "some.text_here:[12,34],[56,78]";
    var match = str.match(/^([\w\d-_.]*):\[(\d+),(\d+)],\[(\d+),(\d+)]/);
    alert("name = " + match[1] + "\n" + 
          "x1 = " + match[2] + "\n" +
          "x2 = " + match[3] + "\n" +
          "y1 = " + match[4] + "\n" +
          "y2 = " + match[5]);
    

    【讨论】:

    • 谢谢 Gumbo,这很好用……但我仍然需要提取的名称。我能够使用 CMS 的正则表达式代替你的,它使 match[1] 包含名称。谢谢!
    【解决方案3】:

    你想要这样的东西:

    /^(\S+):\[(\d+),(\d+)\],\[(\d+),(\d+)\]/
    

    我不确定 JavaScript 是否支持对 caputre 组的命名,但如果支持,您也可以添加它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多