0

I am fairly new with Perl, and even more so with regex. Have been trying to match the following, but without success:

  • First, 3 to 4 letters (ideally case insensitive)
  • Optionally a space (but not mandatory)
  • Then, also optionally a known big-case letter (M) and a number out of 1,2,3

An example of a valid string would be abc, but also DEFG M2. Invalid would be mem M, for example

What I have so far is:

$myExpr ~= m/^[a-z,A-z]{3,4}M[1,2,3]$/i

Not sure how to make the M and numbers optional

titus.andronicus
  • 517
  • 1
  • 7
  • 19
  • 3
    Note that `[A-z]` matches [more than you might expect](http://stackoverflow.com/questions/4923380/difference-between-regex-a-z-and-a-za-z). – Wiktor Stribiżew Dec 10 '15 at 07:58

3 Answers3

1

Group your optional symbols with (?:) and use "zero or one" quantifier ?.

$myExpr =~ m/^[a-zA-Z]{3,4}(?: M[123])?$/

I've also fixed errors in your regexp: you don't use , in character classes - that'd literraly mean "match ,", fixed A-Z range and removed /i modifier, since you didn't say if you need lower case M and first range already covers both small and big letters.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
1

You can use the following regex. You don't need to use comma inside character class []. And also remove i as you need to match with M.

$myExpr ~= m/^[a-zA-z]{3,4}(?: M[123])?$/

If you think your space is optional, then again add a ? after that space too (i.e. (?: ?M[123])).

Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85
1

Why don't you try the following regular expression for it:

$myExpr =~ m/^([a-zA-Z]{3,4})(\s|)(M|)([1-3]|)$/;
  • ([a-zA-Z]{3,4}) - Group of any character in this class: [a-zA-Z] with 3 to 4 repetition.
  • (\s|) - Either there will be a white-space(space) or not.
  • (M|) - Either there will be a Uppercase M or not.
  • ([1-3]|) - Either there will any charter this class: [1-3] or not.

(OR) Try the following

I personally recommend this

$myExpr =~ m/^([a-zA-Z]{3,4})(\s{0,1})(M{0,1})([1-3]{0,1})$/; 
  • ([a-zA-Z]{3,4}) - Group of any character in this class: [a-zA-Z] with 3 to 4 repetition i.e., it should contain minimum of 3 characters and maximum of 4.
  • (\s{0,1}) - Group of \s with 0 to 1 repetition i.e., it's optional.
  • (M{0,1}) - Group of character M with 0 to 1 repetition i.e., it's optional.
  • ([1-3]{0,1}) - Group of any digit from 1 to 3 with 0 to 1 repetition i.e., it's optional.
Manu Mathew
  • 487
  • 4
  • 17