Regular Expression specific to a particular messag

2019-09-21 18:48发布

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

1条回答
Melony?
2楼-- · 2019-09-21 19:24

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.

查看更多
登录 后发表回答