2

Consider this code:

s1="1,2,3,4"; \
s2="1,2,3"; \
sP='^(([1-9][0-9]{0,},){1,2}){1,2}$'; \
[[ "${s1}," =~  $sP ]] && echo "\$s1 matches"; \
[[ "${s2}," =~  $sP ]] && echo "\$s2 matches, but why?"

I am stumped as to why the second string is matched. Is my regex flawed? It is supposed to match either 2 or 4 "elements".

2
  • As I cannot edit my question, here goes: I'd like to match either 1, 2 or 4 instances of the digit sequence (forgot the 1, which requires the "combined" inner quantifier of '{1,2}') – ithaca Apr 17 '16 at 18:24
  • The main point of my question should be: "Why doesn't it work this way"? What did I miss? – ithaca Apr 17 '16 at 18:33
0

To match either 1, or 2 or 4 elements the ERE shoud be modified as follow:

s1="1,2,3,4" ;\
s2="1,2,3" ;\
s3="1" ;\
sP='^[1-9][0-9]{0,},$|^(([1-9][0-9]{0,},){2}){1,2}$' ;\
[[ "${s1}," =~  $sP ]] && printf "\$s1, matches\n" ;\
[[ "${s2}," =~  $sP ]] || printf "\$s2, does not match\n" ;\
[[ "${s3}," =~  $sP ]] && printf "\$s3 matches\n"

Your original ERE could be described iteratively:

[1-9][0-9]{0,}, matches 1, or 2, or 3, or 432, etc.

([1-9][0-9]{0,},){1,2} matches any single or two consecutive sequence described above: 1, or 3, or 1,2, or 10, or 10,432, etc.

(([1-9][0-9]{0,},){1,2}){1,2} matches any 1 or 2 occurrences of the last sequence 1, or 1,2, or 1,2,3, etc.

10
  • Jay, of course; Sorry, I mixed that up in my question, and the example does not indicate that: I'd like to match either 1, 2 or 4 instances (forgot the 1, which requires the "combined" inner quantifier of '{1,2}'); Will comment below original question as well... – ithaca Apr 17 '16 at 18:20
  • @user584029 The top of the answer had been updated with a new ERE. It matches s1 and "1" but not s2. – Jay jargot Apr 17 '16 at 18:28
  • Yes, thanks for the addition of "...1 or 2 or 4 sequence..."; I did not clarify enough - I am looking more for an explanation of "why doesn't it work" (the original) way - in order to be sure I did not misunderstand EREs. – ithaca Apr 17 '16 at 18:31
  • [@]Jay jargot The last line does not leave me entirely convinced: Its inner part (as in the next to last line) yields either a sequence of the kind "d...d," or a sequence of the kind "d...d,d...d,"; allowing one of these sequences to occur once or twice should yield (1) "d...d," or (2) "d...d,d...d," or (3) "d...d,d...d,d...d,d...d,", whereby (2) could be constructed in 2 ways. Again, maybe I did no fully graps EREs... By the way: printf is better! – ithaca Apr 17 '16 at 18:42
  • @user584029 the ERE is made or 2 parts delimited with |. On the left side it matches only one single sequence. On the right side it matches 2 or 4 etc. – Jay jargot Apr 17 '16 at 19:08

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .