Fizzah
Fizzah

Reputation: 63

regular expression for sentence

Please help me for regular expression of string like this sp13-bse-018.

I've got the following inputs:

I have make this regular expression

^((\SP)|(sp)|(FA)|(fa))[1-9][0-9]{2}-{0,1}((BSE)|(bse)|(bcs)|(BCS)|(BTN)|(btn))-{0,1}[0-9]{3}$

but this is not working properly and i also have a lot search for this but i cant get it.

I will be highly thankful for your help.

Upvotes: 0

Views: 64

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

It looks like the culprit is the obligatory non-zero digit [1-9], and once you remove it, your regex will work.

You may shorten your pattern by removing unnecessary groups and using a case insensitive flag:

/^(sp|fa)[0-9]{2}-?(bse|bcs|btn)-?[0-9]{3}$/i

See the regex demo

Details:

  • ^ - start of string
  • (sp|fa) - either sp or fa
  • [0-9]{2} - two ASCII digits
  • -? - an optional (due to ?) hyphen
  • (bse|bcs|btn) - either bse or bcs or btn
  • -? - an optional hyphen
  • [0-9]{3} - 3 ASCII digits
  • $ - end of string.

The case insensitive flag will also allow matching Sp, sP, so if you do not want that behavior, use more alternation: (sp|fa) -> (sp|SP|fa|FA), etc.

Upvotes: 2

Related Questions