2014-10-09 43 views
2

_?在以下rails正則表達式中的含義是什麼?_是什麼?在以下正則表達式中意味着什麼?

/\A_?[a-z]_?(?:[a-z0-9.-]_?)*\z/i 

我試圖破譯正則表達式如下

# regex explained 
# \A : matches the beginning of the string 
# _? :  
# [  : beginning of character group 
# a-z : any lowercase letter 
# ]  : end of character group 
# _? :  
# ( : is a capture group, anything matched within the parens is saved for later use 
# ?: : non-capturing group: matches below, but doesn't store a back-ref 
# [  : beginning of character group 
# a-z : any lowercase letter 
# A-Z : any uppercase letter 
# 0-9 : any digit 
# .  : a fullstop or "any character" ?????? 
# _  : an underscore 
# ]  : end of character group 
# _? :  
#)  : See above 
# *  : zero or more times of the given characters 
# \z : is the end of the string 
+2

'_'沒有特別的意義,它只是一個下劃線。 '_?'是一個可選的下劃線。 – Blender 2014-10-09 04:22:12

回答

1

?意味着先前的表達應該出現0次或1次,類似於*如何意味着它應該匹配0次或更多次,或+表示它應該匹配1次或更多次。

因此,例如,與RE /\A_?[A-Z]?\z/,以下字符串匹配:

  • _O
  • _
  • P

但這些不會:

  • ____
  • A_
  • PP

您發佈的RE原本規定:

  1. 字符串可以以下劃線開頭
  2. 那麼必須有一個小寫字母
  3. 然後可能會有另一個下劃線
  4. 對於字符串的剩餘部分,必須有一個字母,數字,期間,或 - ,其可以後跟下劃線匹配此RE該

實施例的字符串:

  • _a_abcdefg
  • b_abc_def_
  • _qasdf_poiu_
  • a12345_
  • z._.._...._......_
  • u
1

_?裝置_是可選的。

它可以接受_sadasd_sadsadsa_asdasdasd_asdasdsadasdasd,即_分隔的字符串,其中_是可選的。

查看演示。

http://regex101.com/r/hQ1rP0/89

2

_相匹配的下劃線。

?匹配零或一個前面的字符;基本上使前面的字符可選。

因此,_?將匹配一個下劃線,如果它存在,並將匹配沒有它。