Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

grep - Regex match pattern with optional character and min/max length

Match starts with X, which is followed by 3 to 6 capital words or numbers, must containt at least one letter and can have optional dash -. Example of matches:

XABC
XA-BC8D
X-ABC
XB72D-

Example of non-matches:

X123      //no letters
XAB       //too short
XABC-123  //too long
XA--BC    //too many -

I tried with X(?=.{3,6}$)[A-Z0-9]*-?[A-Z0-9]*, but it has many problems. It can match something like X---. Regex should be compatible with grep.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You may use this regex with gnu grep using -P (PCRE):

grep -P '^X(?!([^-]*-){2})(?=[^A-Z]*[A-Z])[A-Zd-]{3,6}$' file

XABC
XA-BC8D
X-ABC
XB72D-

RegEx Demo

RegEx Details:

  • ^: Start
  • X: Match letter X
  • (?!([^-]*-){2}): Negative lookahead to assert that there are never more than one hyphens ahead
  • (?=[^A-Z]*[A-Z]): Positive lookahead to assert presence of at least one uppercase letter ahead
  • [A-Zd-]{3,6}: Match an uppercase letter or digit or - 3 to 6 times
  • $: End

If you don't have gnu grep installed then you may consider this awk:

awk -F- 'NF<3 && /^X[A-Z0-9-]{3,6}$/ && /.[A-Z]/' file

XABC
XA-BC8D
X-ABC
XB72D-

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...