The Old County
The Old County

Reputation: 89

Regex Pattern - Groovy

I need to create a regex - with the following requirements

starts with C, D, F, G, I, M or P has at least one underscore (_)

eg. C6352_3

I've tried the following like this

@Pattern(regexp = '^(\C|\D|\F|\G|\I\|\M|\P)+\_*' , message = "error")

Upvotes: 0

Views: 366

Answers (2)

tim_yates
tim_yates

Reputation: 171074

You could skip regex, and make it readable:

boolean valid(String value) {
   (value?.take(1) in ['C', 'D', 'F', 'G', 'I', 'M', 'P']) && value?.contains('_')
}

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626699

You may use

/^[CDFGIMP][^_\s]*_\S*$/

Or, to only handle word chars (letters, digits and _),

/^[CDFGIMP]\w*_\w*$/

or a bit more efficient one with character class subtraction:

/^[CDFGIMP][\w&&[^_]]*_\w*$/

See the regex demo

Details

  • ^ - start of a string
  • [CDFGIMP] - any char listed in the character set
  • [^_\s]* - zero or more chars other than _ and whitespace
  • \w* - matches 0+ word chars: letters, digits or _ ([\w&&[^_]]* matches 0+ letters and digits only)
  • _ - an underscore
  • \S* - 0+ non-whitespace chars (or \w* will match any letters, digits or _)
  • $ - end of string (or better, \z to only match at the very end of the string).

Upvotes: 1

Related Questions