簡體   English   中英

正則表達式捕獲組

[英]regular expression capture groups

我正在學習正則表達式(當前使用Javascript)。

我的問題是:

我有一長的直線。

在此字符串中,至少有(強制性)三個模式。

結果,我想使用rule.exec()字符串並獲取一個三元素數組。 每個模式分成一個單獨的元素。

我應該如何處理? 目前,我已經達到了目標,但是它起伏不定,並且不知道應該怎么做才能對捕獲進行分組? 是括號()分隔每組正則表達式。

我的正則表達式規則示例:

var rule = /([a-zA-Z0-9].*\s?(@classs?)+\s+[a-zA-Z0-9][^><]*)/g;
var str = "<Home @class www.tarjom.ir><string2 stringValue2>";
var res;
var keys = [];
var values = [];
while((res = rule.exec(str)) != null)
{
    values.push(res[0]);
}
 console.log(values);

// begin to slice them
var sliced = [];
for(item in values)
{
    sliced.push(values[item].split(" "));// converting each item into an array and the assign them to a super array
}



/// Last Updated on 7th of Esfand
console.log(sliced);

和返回結果(使用firefox 27-firebug console.log)

 [["Home", "@class", "www.tarjom.ir"]]

我已經有了所需的東西,我只需要澄清返回模式。

是的, 括號捕獲了它們之間的所有內容 捕獲的組以其開頭的括號編號。 因此,如果/(foo)((bar)baz)/匹配,則第一個捕獲的組將包含foo ,第二個barbaz和第三個bar 在某些方言中,僅對前9個捕獲組進行編號。

捕獲的組可用於反向引用 如果要匹配“ foobarfoo”,則/(foo)bar\\1/將執行此操作,其中\\1表示“我捕獲的第一個組”。

如果只需要括號進行分組,則有一些避免捕獲的方法。 例如,如果要匹配“ foo”或“ foobar”,則/(foo(bar)?)/可以匹配,但可能已在其第二組中捕獲了“ bar”。 如果要避免這種情況,請使用/(foo(?:bar)?)/僅捕獲一個捕獲,即“ foo”或“ foobar”。


您的代碼顯示三個值的原因是由於其他原因。 首先,您進行比賽。 然后,您進行第一次捕獲並將其拆分到一個空間上。 就是您放入結果數組中的內容。 請注意,您一次將整個數組推入其中,因此最終得到一個數組數組。 因此,雙括號。

您的正則表達式匹配(假設我們處於Perl的擴展易讀性模式下):

/                   # matching starts
  (                 # open 1st capturing group
    [a-zA-Z0-9]     # match 1 character that's in a-z, A-Z, or 0-9
    .*              # match as much of any character possible
    \s?             # optionally match a white space (this will generally never happen, since the .* before it will have gobbled it up)
    (               # open 2nd capturing group
      @classs?      # match '@class' or '@classs'
    )+              # close 2n group, matching it once or more
    \s+             # match one or more white space characters
    [a-zA-Z0-9]     # match 1 character that's in a-z, A-Z, or 0-9
    [^><]*          # match any number of characters that's not an angle bracket
  )                 # close 1st capturing group
/g                  # modifiers - g: match globally (repeatedly match throughout entire input)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM