English 中文(简体)
RegEx匹配括号之间的内容
原标题:RegEx to match stuff between parentheses

我很难做到这一点。我有一条像这样的绳子:

something/([0-9])/([a-z])

我需要regex或一种方法来获取括号之间的每个匹配项,并返回一个匹配数组,如:

[
  [0-9],
  [a-z]
]

我使用的正则表达式是/((.+))/,如果只有一个括号集,它似乎与匹配。

如何在JavaScript中使用任何RegExp方法获得如上所述的数组?我只需要返回那个数组,因为数组中返回的项将循环通过以创建URL路由方案。

最佳回答

您需要通过添加<code>来使正则表达式模式不贪婪之后的code>+

默认情况下,*+是贪婪的,因为它们将匹配尽可能长的字符串,忽略字符串中可能发生的任何匹配。

非贪婪使得模式只匹配尽可能短的匹配。

请参阅小心贪婪!以获得更好的解释。

或者,将正则表达式更改为

(([^)]+))

其将匹配本身不包含圆括号的任何圆括号分组。

问题回答

使用以下表达式:

/(([^()]+))/g

例如:

function()
{
    var mts = "something/([0-9])/([a-z])".match(/(([^()]+))/g );
    alert(mts[0]);
    alert(mts[1]);
}

如果s是您的字符串:

s.replace(/^[^(]*(/, "") // trim everything before first parenthesis
 .replace(/)[^(]*$/, "") // trim everything after last parenthesis
 .split(/)[^(]*(/);      // split between parenthesis
var getMatchingGroups = function(s) {
  var r=/((.*?))/g, a=[], m;
  while (m = r.exec(s)) {
    a.push(m[1]);
  }
  return a;
};

getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.