Regular Expression specific to a particular message pattern with mandatory elements

点点圈 提交于 2019-12-25 19:39:13

问题


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:


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.



来源:https://stackoverflow.com/questions/39592440/regular-expression-specific-to-a-particular-message-pattern-with-mandatory-eleme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!