2

What does _? mean in the following rails regex?

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

I have attempted to decipher the regex as follows

# 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
Jeremy Lynch
  • 5,257
  • 2
  • 41
  • 55

3 Answers3

2

_ matches an underscore.

? matches zero or one of the preceeding character; basically making the preceeding character optional.

So _? will match one underscore if it is present, and will match without it.

Substantial
  • 6,574
  • 2
  • 27
  • 38
1

? means that the previous expression should appear 0 or 1 times, similarly to how * means it should match 0 or more times, or + means it should match 1 or more times.

So, for example, with the RE /\A_?[A-Z]?\z/, the following strings will match:

  • _O
  • _
  • P

but these will not:

  • ____
  • A_
  • PP

The RE you posted originally states:

  1. The string may begin with an underscore
  2. Then there must be a lowercase letter
  3. Then there may be another underscore
  4. For the rest of the string, there must be a letter, number, period, or -, which may be followed by an underscore

Example strings that match this RE:

  • _a_abcdefg
  • b_abc_def_
  • _qasdf_poiu_
  • a12345_
  • z._.._...._......_
  • u
fluffy
  • 4,460
  • 28
  • 58
1

_? means _ is optional.

It can accept _sadasd_sadsadsa_asdasdasd_ or asdasdsadasdasd i.e _ separated strings where _ is optional.

See demo.

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

vks
  • 63,206
  • 9
  • 78
  • 110