Regular Expression Basics

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

ElementDescription
.Specifies any character except a newline character (\n)
\dSpecifies any decimal digit
\DSpecifies any nondigit
\sSpecifies any whitespace character
\SSpecifies any non-whitespace character
\wSpecifies any word character
\WSpecifies any nonword character
^Specifies the beginning of the string or line
\ASpecifies the beginning of the string
$Specifies the end of the string or line
\zSpecifies 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 TypeRegular 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-./?%=]*)?$
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.