开发者

How to write a regular expression to match a set of values?

开发者 https://www.devze.com 2022-12-13 19:00 出处:网络
I want to check if my string holds following value 开发者_运维百科or not: For samples: 4850324810111981066060

I want to check if my string holds following value 开发者_运维百科or not:

For samples:

  • 4850324810111981066060
  • 50104810111981066060

My condition is

48-57(1 or more time)32(or)10(or)13(then)48(then)32(or)10(or)13(then)111981066060  

Question: How to write regular expression for above condition. Parenthesis indicate occurrence.


(4[8-9]|5[0-7])+(32|10|13)48(32|10|13)111981066060


Check out Expresso - it allows you to build and test your regexs, and creates a C# code snippet or a .NET assembly for you right away. Highly recommended!


Regex regex = new Regex(@"(?:4[89]|5[0-7])+(?:32|10|13)48(?:32|10|13)111981066060");
regex.Match(string);

Didnt test though!


You can test regular expressions in .NET online using Nregex


This this:

(48|49|50|51|52|53|54|55|56|57)+(32|10|13)48(32|10|13)111981066060

EDIT: Just saw Paul answer and this really can be shortened to

(4[89]|5[0-7])+(32|10|13)48(32|10|13)111981066060

Only difference between hos and mine approaches is: he doesn't keeps grouping information (as that isn't required) and I don't care for ignore them.


You can start with the following and see if you need to make imprevements

(4[89]|5[0-7])+(32|10|13)48(32|10|13)111981066060

it might be better to split up into fields and check those fields against your business logic instead of relying on a static regexp like the above.

0

精彩评论

暂无评论...
验证码 换一张
取 消