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:
- (
- numbers开发者_开发技巧
- )
- empty space
- numbers
- -
- 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
精彩评论