One of the most common regular expression operators is ? quantifier.
? is a quantifier that matches the preceding item 0 or 1 time.
? means optional.
An item is either a single character or a complex structure of characters in square brackets.
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Regex.Match("abcd", @"abcd?d").Success);
Console.WriteLine(Regex.Match("abcdc", @"abcd?d").Success);
Console.WriteLine(Regex.Match("abcdcd", @"abcd?d").Success);
}
}
The output:
True
True
True
| Element | Description |
|---|---|
| . | Specifies any character except a newline character (\n) |
| \d | Specifies any decimal digit |
| \D | Specifies any nondigit |
| \s | Specifies any whitespace character |
| \S | Specifies any non-whitespace character |
| \w | Specifies any word character |
| \W | Specifies any nonword character |
| ^ | Specifies the beginning of the string or line |
| \A | Specifies the beginning of the string |
| $ | Specifies the end of the string or line |
| \z | Specifies the end of the string |
| | | Matches one of the expressions separated by the vertical bar (pipe symbol) |
| [abc] | Specifies a match with one of the specified characters |
| [^abc] | Specifies a match with any one character except those specified |
| [a-z] | Specifies a match with any one character in the specified range |
| ( ) | Identifies a subexpression so that it's treated as a single element |
| ? | Specifies one or zero occurrencesof the previous character or subexpression; |
| * | Specifies zero or more occurrences of the previous character or subexpression; |
| + | Specifies one or more occurrences of the previous character or subexpression; |
| {n} | Specifies exactly n occurrences of the preceding character or subexpression; |
| {n,} | Specifies a minimum of n occurrences of the preceding character or subexpression; |
| {n, m} | Specifies a minimum of n and a maximum of m occurrences of the preceding character; |
Commonly Used Regular Expressions
| Input Type | Regular Expression |
|---|---|
| Numeric input | ^\d+$ |
| Personal identification number (PIN) | ^\d{4}$ |
| Simple password | ^\w{6,8}$ |
| Credit card number | ^\d{4}-?\d{4}-?\d{4}-?\d{4}$ |
| E-mail address | ^[\w-]+@([\w-]+\.)+[\w-]+$ |
| HTTP or HTTPS URL | ^https?://([\w-]+\.)+ [\w-]+(/[\w-./?%=]*)?$ |
| w_w_w__.___j___a___va_2___s__.c_o__m___ | Contact Us |
| Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
| All other trademarks are property of their respective owners. |