code_t
code_t

Reputation: 49

how to group a special character and a letter in regex in ruby?

I have regular expression like this in ruby

%r{
  (ST)
  ([A-Z]) ?
  (#{A_VAL})
  -?
  (T)?
}x

Now ,I don't want my regex to accept any string that ends with "-" .So, for example it should accept
1)"STCA1-T"
2)"STCA1T"
But it shouldn't accept "STCA1-"

Upvotes: 2

Views: 239

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You may use

/\AST[A-Z]?(#{A_VAL})(?:-?T)?\z/

Details

  • \A - start of string
  • ST - an ST substring
  • [A-Z]? - an optional ASCII letter
  • (#{A_VAL}) - Group 1 (if there is a single alternative, just one string, and you do not need this value later, you may omit the capturing parentheses): a pattern inside A_VAL variable
  • (?:-?T)? - an optional non-capturing group that matches an optional - and an obligatory T (i.e. it matches -T or T 1 or 0 times)
  • \z - end of string.

Upvotes: 3

Related Questions