开发者

Regular Expressions of two alternate patterns in single string

I'm beginner in regular expressions, so your help will be very big for me. I have this pattern string:

@"^\(\d\d\d\) \d\d\d-\d\d\d\d$"

which matches phone numbers only in this format: (555) 555-5555 but what I really need is the sequence to be followed, not the exact number of characters and positions. So I need the following sequence:

  1. (
  2. numbers开发者_开发技巧
  3. )
  4. empty space
  5. numbers
  6. -
  7. numbers

Is this possible? Thanks.


So, something like this?

^\(\d+\)\s*\d+-\d+

1 Open Paren
2 Numbers
3 Close Paren
4 Space
5 Numbers
6 Dash
7 Numbers

EDIT: Added the (none or more) quantifier to the space after the close paren


Use + instead of fixed number of characters?

@"^\(\d+\) \d+-\d+$"


If you don't care how many numbers are in the area code, or the number, you can use this:

^\s*\(\s*\d+\s*\)\s*\d+\s*-\s*\d+\s*$

This allows for any amount of white space (including no white space) around the parentheses and dash, and at the beginning and end of the data.

If you do care how many numbers, use \d{1,3}, for example, instead of \d+. This allows for 1-3 digits in one place.


You should use \d{x,y} to represent a sequence of numbers at least x long and at most y long. Example:

@"^\(\d{1,3}\) \d{3,5}-\d{4,6}$"

For more details see Regex Quantifiers

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜