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

Categories

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

regex - Regular Expression specific to a particular message pattern with mandatory elements

As I'm pretty new to Regular Expression, I'm looking for a regular expression which will validate whether entire string is separated by | and there will be values with $ followed by an integer.

Valid Values:

ABC=$2|CDE=$1|Msg=$4|Ph.No=$3|TIME=$5
ABC=$2|CDE=$1|Msg123=$4|Ph.No=$3|TIME_23=$5    
abc=$2|123=$1|cfg=$4|Ph.No=$3

Invalid Values:

ABC=$2CDE=$1Msg=$4    
ABC=2|CDE=1|Msg123=$4|Ph.No=$3|TIME_23=$5    
abc$2|123$1|cfg$4|Ph.No=$3    
Msg123=$ |Ph.No=$ |TIME_23=5    
abcdefgh|1234|eghjik    
Msg123=$*|Ph.No=$()|TIME_23=$5    
Msg123=$a|Ph.No=$b|TIME_23=$p
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This will do it for you:

^[w.]+=$d+(?:|[w.]+=$d+)*$

It matches at least one word character or . followed by an =, $ and a digit. Then, optionally, a | followed by the first sequence again. This optional part can be repeated any number of times.

See it here at regex101.

Edit

Allow multi-digit numbers.

Edit 2

If you need to check the range being 0-12 use

^[w.]+=$(?:d|1[012])(?:|[w.]+=$(?:d|1[012]))*$

Here's an example.

Edit 3

As OP needed pure POSIX, here's what we ended up with:

^[A-Za-z0-9_.]+=$(1[012]|[0-9])(|[A-Za-z0-9_.]+=$(1[012]|??[0-9]))*$

No shorthand character classes nor non capturing groups.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...