2015-04-15 50 views
1

如何將一個命名組與x正則表達式修飾符一起使用?命名組+ x修飾符

作品:

/(?<number>\d+)/ =~ 'hello here is a number 3298472398723' 
puts number 

作品:

regexp =/
    number # this is a word 
    \s  # this is a space 
    (\d+) # this is a bunch of numbers 
/x 
regexp =~ 'hello here is a number 3298472398723' 
puts $1 

不起作用:

regexp =/
    number # this is a word 
    \s  # this is a space 
    (?<number>\d+) # this is a bunch of numbers 
/x 
regexp =~ 'hello here is a number 3298472398723' 
puts number 

我在做什麼錯?

回答

4

你在攪拌東西。後一個例子中的puts number不起作用,不是因爲它擴展了正則表達式,而是因爲它不是內聯的。

$~[:number]Regexp.last_match[:number]總是工作。

直接引用僅適用於內聯正則表達式:

▶/
▷ number # this is a word 
▷ \s  # this is a space 
▷ (?<number>\d+) # this is a bunch of numbers 
▷ /x =~ 'hello here is a number 11111' 
#⇒ 16 
▶ number 
#⇒ "11111" 

這完全適用於擴展的正則表達式,因爲它是內聯。

UPD感謝@Stefan,這裏是從documentation更精確的要求:

這種分配在Ruby語法分析器來實現。解析器檢測到該作業爲regexp-literal =~ expression。正則表達式必須是沒有插值的文字,並放置在左側。

+4

從[documentation](http://ruby-doc.org/core-2.1.1/Regexp.html#method-i-3D-7E):*「正則表達式必須是沒有插值的文字並放在左側。「* – Stefan

+0

@Stefan謝謝,更新了一個答案。 – mudasobwa

+0

@ Fuser97381我的名字不是馬茨,順便說一句。 – mudasobwa