[英]Is it normal for a RegEx to give more than one matching for a single match?
如果問題標題有點混亂,我很抱歉,但在這里我將詳細闡述我的困惑。
我想用正則表達式來匹配apple、orange、mango、apple[(可以有任何數字或空)]、orange[(可以有任何數字或空)]。 (注意芒果不會有 [])。 以下是一些有效的例子:
這是我想出的正則表達式:
/^(mango|(apple|orange)(\[[1-9][0-9]*\])?)$
此正則表達式有效,但通常會提供 1 個以上的匹配組。 例如apple[15]
將給出 1. apple[15]
2. apple[15]
3. [15]
實際上行為是正常的,因為我有 many ()
,它創建了很多組,但我想知道我是否使用正確的方法來構造這個正則表達式? 因為它只是為單場比賽提供了太多結果。
此外,有什么方法可以優化這個正則表達式嗎? 這個正則表達式相當簡單,但看起來很復雜。
謝謝你。
它匹配那些子組,因為這就是()
所做的。 如果要將項目組合在一起而不將它們與輸出匹配,請使用非捕獲組(?:)
。 例如: (?:apple|orange)
將匹配 apple 或 orange,但不會捕獲要輸出的組。
如果您只想在沒有子組的情況下捕獲整個匹配項,請執行以下操作:
^mango$|^(?:apple|orange)(?:\[(?:[1-9][0-9]*)?\])?$
var strArr = [ 'apple', 'orange', 'apple[]', 'orange[]', 'apple[15]', 'apple[05]', 'mango[]', 'mango' ]; var re = /^mango$|^(?:apple|orange)(?:\\[(?:[1-9][0-9]*)?\\])?$/; strArr.forEach(function(str) { document.body.insertAdjacentHTML('beforeend', str + ' - match? ' + re.test(str) + '<br>'); });
鐵路圖:
在您的正則表達式中,您要聲明 (G1|(G2)(G3))。 這就是為什么當你匹配時你會得到一個包含四個值的數組:
1. apple[15] The whole match
2. apple[15] G1 (mango|(apple|orange)(\[1-9][0-9]*\])?)
3. apple G2 (apple|orange)
4. [15] G3 (\[[1-9][0-9]*\])?
如果您將正則表達式更改為/^(mango)|(apple|orange)(\\[[1-9][0-9]*\\])?$/
您將得到相同的結果,除了 #2 from除非您將mango
作為輸入參數,否則上述內容將是未定義的。 請注意,表達式仍將接受mango[123]
,但匹配項將不包括數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.