.NET Framework 4 Character Classes A character class defines a set of characters, any one of which can occur in an input string for a match to succeed. The regular expression language in the .NET Framework supports the following character classes: Positive character groups. A character in the input string must match one of a specified set of characters. For more information, see Positive Character Group. Negative character groups. A character in the input string must not match one of a specified set of characters. For more information, see Negative Character Group. Any character. The . (dot or period) character in a regular expression is a wildcard character that matches any character except \n. For more information, see Any Character. A general Unicode category or named block. A character in the input string must be a member of a particular Unicode category or must fall within a contiguous range of Unicode characters for a match to succeed. For more information, see Unicode Category or Unicode Block. A negative general Unicode category or named block. A character in the input string must not be a member of a particular Unicode category or must not fall within a contiguous range of Unicode characters for a match to succeed. For more information, see Negative Unicode Category or Unicode Block. A word character. A character in the input string can belong to any of the Unicode categories that are appropriate for characters in words. For more information, see Word Character. A non-word character. A character in the input string can belong to any Unicode category that is not a word character. For more information, see Non-Word Character. A white-space character. A character in the input string can be any Unicode separator character, as well as any one of a number of control characters. For more information, see White-Space Character. A non-white-space character. A character in the input string can be any character that is not a white-space character. For more information, see Non-White-Space Character. A decimal digit. A character in the input string can be any of a number of characters classified as Unicode decimal digits. For more information, see Decimal Digit Character. A non-decimal digit. A character in the input string can be anything other than a Unicode decimal digit. For more information, see Decimal Digit Character.
The .NET Framework supports character class subtraction expressions, which enables you to define a set of characters as the result of excluding one character class from another character class. For more information, see Character Class Subtraction.

Positive Character Group: [ ]
A positive character group specifies a list of characters, any one of which may appear in an input string for a match to occur. This list of characters may be specified individually, as a range, or both. The syntax for specifying a list of individual characters is as follows: [character_group] where character_group is a list of the individual characters that can appear in the input string for a match to succeed. character_group can consist of any combination of one or more literal characters, escape characters, or character classes. The syntax for specifying a range of characters is as follows:
[firstCharacter-lastCharacter]
where firstCharacter is the character that begins the range and lastCharacter is the character that ends the range. A character range is a contiguous series of characters defined by specifying the first character in the series, a hyphen (-), and then the last character in the series. Two characters are contiguous if they have adjacent Unicode code points. Some common regular expression patterns that contain positive character classes are listed in the following table. Pattern | Description |
|---|
[aeiou] | Match all vowels. | [\p{P}\d] | Match all punctuation and decimal digit characters. | [\s\p{P}] | Match all white-space and punctuation. |
The following example defines a positive character group that contains the characters "a" and "e" so that the input string must contain the words "grey" or "gray" followed by another word for a match to occur.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "gr[ae]y\s\S+?[\s|\p{P}]"
Dim input As String = "The gray wolf jumped over the grey wall."
Dim matches As MatchCollection = Regex.Matches(input, pattern)
For Each match As Match In matches
Console.WriteLine(match.Value)
Next
End Sub
End Module
' The example displays the following output:
' gray wolf
' grey wall.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"gr[ae]y\s\S+?[\s|\p{P}]";
string input = "The gray wolf jumped over the grey wall.";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
Console.WriteLine(match.Value);
}
}
// The example displays the following output:
// gray wolf
// grey wall.
The regular expression gr[ae]y\s\S+?[\s|\p{P}] is defined as follows: Pattern | Description |
|---|
gr | Match the literal characters "gr". | [ae] | Match either an "a" or an "e". | y\s | Match the literal character "y" followed by a white-space character. | \S+? | Match one or more non-white-space characters, but as few as possible. | [\s|\p{P}] | Match either a white-space character or a punctuation mark. |
The following example matches words that begin with any capital letter. It uses the subexpression [A-Z] to represent the range of capital letters from A to Z.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b[A-Z]\w*\b"
Dim input As String = "A city Albany Zulu maritime Marseilles"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Value)
Next
End Sub
End Module
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b[A-Z]\w*\b";
string input = "A city Albany Zulu maritime Marseilles";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine(match.Value);
}
}
// The example displays the following output:
// A
// Albany
// Zulu
// Marseilles
The regular expression \b[A-Z]\w*\b is defined as shown in the following table. Pattern | Description |
|---|
\b | Start at a word boundary. | [A-Z] | Match any uppercase character from A to Z. | \w* | Match zero or more word characters. | \b | Match a word boundary. |
Back to Top

Negative Character Group: [^]
A negative character group specifies a list of characters that must not appear in an input string for a match to occur. The list of characters may be specified individually, as a range, or both. The syntax for specifying a list of individual characters is as follows: [^character_group] where character_group is a list of the individual characters that cannot appear in the input string for a match to succeed. character_group can consist of any combination of one or more literal characters, escape characters, or character classes. The syntax for specifying a range of characters is as follows: [^firstCharacter-lastCharacter] where firstCharacter is the character that begins the range, and lastCharacter is the character that ends the range. A character range is a contiguous series of characters defined by specifying the first character in the series, a hyphen (-), and then the last character in the series. Two characters are contiguous if they have adjacent Unicode code points. Two or more character ranges can be concatenated. For example, to specify the range of decimal digits from "0" through "9", the range of lowercase letters from "a" through "f", and the range of uppercase letters from "A" through "F", use [0-9a-fA-F]. The leading carat character (^) in a negative character group is mandatory and indicates the character group is a negative character group instead of a positive character group. Important |
|---|
A negative character group in a larger regular expression pattern is not a zero-width assertion. That is, after evaluating the negative character group, the regular expression engine advances one character in the input string. |
Some common regular expression patterns that contain negative character groups are listed in the following table. Pattern | Description |
|---|
[^aeiou] | Match all characters except vowels. | [^\p{P}\d] | Match all characters except punctuation and decimal digit characters. |
The following example matches any word that begins with the characters "th" and is not followed by an "o".
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\bth[^o]\w+\b"
Dim input As String = "thought thing though them through thus " + _
"thorough this"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Value)
Next
End Sub
End Module
' The example displays the following output:
' thing
' them
' through
' thus
' this
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\bth[^o]\w+\b";
string input = "thought thing though them through thus thorough this";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine(match.Value);
}
}
// The example displays the following output:
// thing
// them
// through
// thus
// this
The regular expression \bth[^o]\w+\b is defined as shown in the following table. Pattern | Description |
|---|
\b | Start at a word boundary. | th | Match the literal characters "th". | [^o] | Match any character that is not an "o". | \w+ | Match one or more word characters. | \b | End at a word boundary. |
Back to Top

Any Character: .
The period character (.) matches any character except \n (the newline character, \u000A), with the following two qualifications: If a regular expression pattern is modified by the RegexOptions..::.Singleline option, or if the portion of the pattern that contains the . character class is modified by the s option, . matches any character. For more information, see Regular Expression Options. The following example illustrates the different behavior of the . character class by default and with the RegexOptions..::.Singleline option. The regular expression ^.+ starts at the beginning of the string and matches every character. By default, the match ends at the end of the first line; the regular expression pattern matches the carriage return character, \r or \u000D, but it does not match \n. Because the RegexOptions..::.Singleline option interprets the entire input string as a single line, it matches every character in the input string, including \n.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "^.+"
Dim input As String = "This is one line and" + vbCrLf + "this is the second."
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(Regex.Escape(match.Value))
Next
Console.WriteLine()
For Each match As Match In Regex.Matches(input, pattern, RegexOptions.SingleLine)
Console.WriteLine(Regex.Escape(match.Value))
Next
End Sub
End Module
' The example displays the following output:
' This\ is\ one\ line\ and\r
'
' This\ is\ one\ line\ and\r\nthis\ is\ the\ second\.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = "^.+";
string input = "This is one line and" + Environment.NewLine + "this is the second.";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine(Regex.Escape(match.Value));
Console.WriteLine();
foreach (Match match in Regex.Matches(input, pattern, RegexOptions.Singleline))
Console.WriteLine(Regex.Escape(match.Value));
}
}
// The example displays the following output:
// This\ is\ one\ line\ and\r
//
// This\ is\ one\ line\ and\r\nthis\ is\ the\ second\.
Note |
|---|
Because it matches any character except \n, the . character class also matches \r (the carriage return character, \u000D). |
In a positive or negative character group, a period is treated as a literal period character, and not as a character class. For more information, see Positive Character Group and Negative Character Group earlier in this topic. The following example provides an illustration by defining a regular expression that includes the period character (.) both as a character class and as a member of a positive character group. The regular expression \b.*[.?!;:](\s|\z) begins at a word boundary, matches any character until it encounters one of four punctuation marks, including a period, and then matches either a white-space character or the end of the string.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As STring = "\b.*[.?!;:](\s|\z)"
Dim input As String = "this. what: is? go, thing."
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Value)
Next
End Sub
End Module
' The example displays the following output:
' this. what: is? go, thing.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b.*[.?!;:](\s|\z)";
string input = "this. what: is? go, thing.";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine(match.Value);
}
}
// The example displays the following output:
// this. what: is? go, thing.
Note |
|---|
Because it matches any character, the . language element is often used with a lazy quantifier if a regular expression pattern attempts to match any character multiple times. For more information, see Quantifiers. |
Back to Top

Unicode Category or Unicode Block: \p{}
The Unicode standard assigns each character a general category. For example, a particular character can be an uppercase letter (represented by the Lu category), a decimal digit (the Nd category), a math symbol (the Sm category), or a paragraph separator (the Zl category). Specific character sets in the Unicode standard also occupy a specific range or block of consecutive code points. For example, the basic Latin character set is found from \u0000 through \u007F, while the Arabic character set is found from \u0600 through \u06FF. The regular expression construct \p{name} matches any character that belongs to a Unicode general category or named block, where name is the category abbreviation or named block name. For a list of category abbreviations, see the Supported Unicode General Categories section later in this topic. For a list of named blocks, see the Supported Named Blocks section later in this topic. The following example uses the \p{name} construct to match both a Unicode general category (in this case, the Pd, or Punctuation,Dash category) and a named block (the IsGreek and IsBasicLatin named blocks).
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+"
Dim input As String = "Κατα Μαθθαίον - The Gospel of Matthew"
Console.WriteLine(Regex.IsMatch(input, pattern)) ' Displays True.
End Sub
End Module
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+";
string input = "Κατα Μαθθαίον - The Gospel of Matthew";
Console.WriteLine(Regex.IsMatch(input, pattern)); // Displays True.
}
}
The regular expression \b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+ is defined as shown in the following table. Pattern | Description |
|---|
\b | Start at a word boundary. | \p{IsGreek}+ | Match one or more Greek characters. | (\s)? | Match zero or one white-space character. | (\p{IsGreek}+(\s)?)+ | Match the pattern of one or more Greek characters followed by zero or one white-space characters one or more times. | \p{Pd} | Match a Punctuation, Dash character. | \s | Match a white-space character. | \p{IsBasicLatin}+ | Match one or more basic Latin characters. | (\s)? | Match zero or one white-space character. | (\p{IsBasicLatin}+(\s)?)+ | Match the pattern of one or more basic Latin characters followed by zero or one white-space characters one or more times. |
Back to Top

Negative Unicode Category or Unicode Block: \P{}
The Unicode standard assigns each character a general category. For example, a particular character can be an uppercase letter (represented by the Lu category), a decimal digit (the Nd category), a math symbol (the Sm category), or a paragraph separator (the Zl category). Specific character sets in the Unicode standard also occupy a specific range or block of consecutive code points. For example, the basic Latin character set is found from \u0000 through \u007F, while the Arabic character set is found from \u0600 through \u06FF. The regular expression construct \P{name} matches any character that does not belong to a Unicode general category or named block, where name is the category abbreviation or named block name. For a list of category abbreviations, see the Supported Unicode General Categories section later in this topic. For a list of named blocks, see the Supported Named Blocks section later in this topic. The following example uses the \P{name} construct to remove any currency symbols (in this case, the Sc, or Symbol, Currency category) from numeric strings.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "(\P{Sc})+"
Dim values() As String = { "$164,091.78", "£1,073,142.68", "73¢", "€120"}
For Each value As String In values
Console.WriteLine(Regex.Match(value, pattern).Value)
Next
End Sub
End Module
' The example displays the following output:
' 164,091.78
' 1,073,142.68
' 73
' 120
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"(\P{Sc})+";
string[] values = { "$164,091.78", "£1,073,142.68", "73¢", "€120" };
foreach (string value in values)
Console.WriteLine(Regex.Match(value, pattern).Value);
}
}
// The example displays the following output:
// 164,091.78
// 1,073,142.68
// 73
// 120
The regular expression pattern (\P{Sc})+ matches one or more characters that are not currency symbols; it effectively strips any currency symbol from the result string. Back to Top

Word Character: \w
\w matches any word character. A word character is a member of any of the Unicode categories listed in the following table. Category | Description |
|---|
Ll | Letter, Lowercase | Lu | Letter, Uppercase | Lt | Letter, Titlecase | Lo | Letter, Other | Lm | Letter, Modifier | Nd | Number, Decimal Digit | Pc | Punctuation, Connector. This category includes ten characters, the most commonly used of which is the LOWLINE character (_), u+005F. |
If ECMAScript-compliant behavior is specified, \w is equivalent to [a-zA-Z_0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options. Note |
|---|
Because it matches any word character, the \w language element is often used with a lazy quantifier if a regular expression pattern attempts to match any word character multiple times, followed by a specific word character. For more information, see Quantifiers. |
The following example uses the \w language element to match duplicate characters in a word. The example defines a regular expression pattern, (\w)\1, which can be interpreted as follows. Element | Description |
|---|
(\w) | Match a word character. This is the first capturing group. | \1 | Match the value of the first capture. |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "(\w)\1"
Dim words() As String = { "trellis", "seer", "latter", "summer", _
"hoarse", "lesser", "aardvark", "stunned" }
For Each word As String In words
Dim match As Match = Regex.Match(word, pattern)
If match.Success Then
Console.WriteLine("'{0}' found in '{1}' at position {2}.", _
match.Value, word, match.Index)
Else
Console.WriteLine("No double characters in '{0}'.", word)
End If
Next
End Sub
End Module
' The example displays the following output:
' 'll' found in 'trellis' at position 3.
' 'ee' found in 'seer' at position 1.
' 'tt' found in 'latter' at position 2.
' 'mm' found in 'summer' at position 2.
' No double characters in 'hoarse'.
' 'ss' found in 'lesser' at position 2.
' 'aa' found in 'aardvark' at position 0.
' 'nn' found in 'stunned' at position 3.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"(\w)\1";
string[] words = { "trellis", "seer", "latter", "summer",
"hoarse", "lesser", "aardvark", "stunned" };
foreach (string word in words)
{
Match match = Regex.Match(word, pattern);
if (match.Success)
Console.WriteLine("'{0}' found in '{1}' at position {2}.",
match.Value, word, match.Index);
else
Console.WriteLine("No double characters in '{0}'.", word);
}
}
}
// The example displays the following output:
// 'll' found in 'trellis' at position 3.
// 'ee' found in 'seer' at position 1.
// 'tt' found in 'latter' at position 2.
// 'mm' found in 'summer' at position 2.
// No double characters in 'hoarse'.
// 'ss' found in 'lesser' at position 2.
// 'aa' found in 'aardvark' at position 0.
// 'nn' found in 'stunned' at position 3.
Back to Top

Non-Word Character: \W
\W matches any non-word character. The \W language element is equivalent to the following character class:
[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}]
In other words, it matches any character except for those listed in the following table. Category | Description |
|---|
Ll | Letter, Lowercase | Lu | Letter, Uppercase | Lt | Letter, Titlecase | Lo | Letter, Other | Lm | Letter, Modifier | Nd | Number, Decimal Digit | Pc | Punctuation, Connector. This category includes ten characters, the most commonly used of which is the LOWLINE character (_), u+005F. |
If ECMAScript-compliant behavior is specified, \W is equivalent to [^a-zA-Z_0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options. Note |
|---|
Because it matches any non-word character, the \W language element is often used with a lazy quantifier if a regular expression pattern attempts to match any non-word character multiple times followed by a specific non-word character. For more information, see Quantifiers. |
The following example illustrates the \w character class. It defines a regular expression pattern, \b(\w+)(\W){1,2}, that matches a word followed by one or more non-word characters, such as white space or punctuation. The regular expression is interpreted as shown in the following table. Element | Description |
|---|
\b | Begin the match at a word boundary. | (\w+) | Match one or more word characters. This is the first capturing group. | (\w){1,2} | Match a non-word character either one or two times. This is the second capturing group. |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b(\w+)(\W){1,2}"
Dim input As String = "The old, grey mare slowly walked across the narrow, green pasture."
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Value)
Console.Write(" Non-word character(s):")
Dim captures As CaptureCollection = match.Groups(2).Captures
For ctr As Integer = 0 To captures.Count - 1
Console.Write("'{0}' (\u{1}){2}", captures(ctr).Value, _
Convert.ToUInt16(captures(ctr).Value.Chars(0)).ToString("X4"), _
If(ctr < captures.Count - 1, ", ", ""))
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' The
' Non-word character(s):' ' (\u0020)
' old,
' Non-word character(s):',' (\u002C), ' ' (\u0020)
' grey
' Non-word character(s):' ' (\u0020)
' mare
' Non-word character(s):' ' (\u0020)
' slowly
' Non-word character(s):' ' (\u0020)
' walked
' Non-word character(s):' ' (\u0020)
' across
' Non-word character(s):' ' (\u0020)
' the
' Non-word character(s):' ' (\u0020)
' narrow,
' Non-word character(s):',' (\u002C), ' ' (\u0020)
' green
' Non-word character(s):' ' (\u0020)
' pasture.
' Non-word character(s):'.' (\u002E)
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b(\w+)(\W){1,2}";
string input = "The old, grey mare slowly walked across the narrow, green pasture.";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
Console.Write(" Non-word character(s):");
CaptureCollection captures = match.Groups[2].Captures;
for (int ctr = 0; ctr < captures.Count; ctr++)
Console.Write(@"'{0}' (\u{1}){2}", captures[ctr].Value,
Convert.ToUInt16(captures[ctr].Value[0]).ToString("X4"),
ctr < captures.Count - 1 ? ", " : "");
Console.WriteLine();
}
}
}
// The example displays the following output:
// The
// Non-word character(s):' ' (\u0020)
// old,
// Non-word character(s):',' (\u002C), ' ' (\u0020)
// grey
// Non-word character(s):' ' (\u0020)
// mare
// Non-word character(s):' ' (\u0020)
// slowly
// Non-word character(s):' ' (\u0020)
// walked
// Non-word character(s):' ' (\u0020)
// across
// Non-word character(s):' ' (\u0020)
// the
// Non-word character(s):' ' (\u0020)
// narrow,
// Non-word character(s):',' (\u002C), ' ' (\u0020)
// green
// Non-word character(s):' ' (\u0020)
// pasture.
// Non-word character(s):'.' (\u002E)
Because the Group object for the second capturing group contains only a single captured non-word character, the example retrieves all captured non-word characters from the CaptureCollection object that is returned by the Group..::.Captures property. Back to Top

White-Space Character: \s
\s matches any white-space character. It is equivalent to the escape sequences and Unicode categories listed in the following table. Category | Description |
|---|
\f | The form feed character, \u000C. | \n | The newline character, \u000A. | \r | The carriage return character, \u000D. | \t | The tab character, \u0009. | \v | The vertical tab character, \u000B. | \x85 | The ellipsis or NEXT LINE (NEL) character (…), \u0085. | \p{Z} | Matches any separator character. |
If ECMAScript-compliant behavior is specified, \s is equivalent to [\f\n\r\t\v]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options. The following example illustrates the \s character class. It defines a regular expression pattern, \b\w+(e)*s(\s|$), that matches a word ending in either "s" or "es" followed by either a white-space character or the end of the input string. The regular expression is interpreted as shown in the following table. Element | Description |
|---|
\b | Begin the match at a word boundary. | \w+ | Match one or more word characters. | (e)* | Match an "e" either zero or one time. | s | Match an "s". | (\s|$) | Match either a whitespace character or the end of the input string. |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b\w+(e)*s(\s|$)"
Dim input As String = "matches stores stops leave leaves"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Value)
Next
End Sub
End Module
' The example displays the following output:
' matches
' stores
' stops
' leaves
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b\w+(e)*s(\s|$)";
string input = "matches stores stops leave leaves";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine(match.Value);
}
}
// The example displays the following output:
// matches
// stores
// stops
// leaves
Back to Top

Non-White-Space Character: \S
\S matches any non-white-space character. It is equivalent to the [^\f\n\r\t\v\x85\p{Z}] regular expression pattern, or the opposite of the regular expression pattern that is equivalent to \s, which matches white-space characters. For more information, see White-Space Character: \s. If ECMAScript-compliant behavior is specified, \S is equivalent to [^ \f\n\r\t\v]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options. The following example illustrates the \S language element. The regular expression pattern \b(\S+)\s* matches strings that are delimited by white-space characters. The second element in the match's GroupCollection object contains the matched string. The regular expression can be interpreted as shown in the following table. Element | Description |
|---|
\b | Begin the match at a word boundary. | (\S+) | Match one or more non-white-space characters. This is the first capturing group. | \s* | Match zero or one white-space character. |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b(\S+)\s*"
Dim input As String = "This is the first sentence of the first paragraph. " + _
"This is the second sentence." + vbCrLf + _
"This is the only sentence of the second paragraph."
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Groups(1))
Next
End Sub
End Module
' The example displays the following output:
' This
' is
' the
' first
' sentence
' of
' the
' first
' paragraph.
' This
' is
' the
' second
' sentence.
' This
' is
' the
' only
' sentence
' of
' the
' second
' paragraph.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b(\S+)\s*";
string input = "This is the first sentence of the first paragraph. " +
"This is the second sentence.\n" +
"This is the only sentence of the second paragraph.";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine(match.Groups[1]);
}
}
// The example displays the following output:
// This
// is
// the
// first
// sentence
// of
// the
// first
// paragraph.
// This
// is
// the
// second
// sentence.
// This
// is
// the
// only
// sentence
// of
// the
// second
// paragraph.
Back to Top

Decimal Digit Character: \d
\d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets. If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options. The following example illustrates the \d language element. It tests whether an input string represents a valid telephone number in the United States and Canada. The regular expression pattern ^(\(*\d{3}\)*[\s-])*\d{3}-\d{4}$ is defined as shown in the following table. Element | Description |
|---|
^ | Begin the match at the beginning of the input string. | \(* | Match zero or one literal "(" character. | \d{3} | Match three decimal digits. | \)* | Match zero or one literal ")" character. | [\s-] | Match a hyphen or a white-space character. | (\(*\d{3}\)*[\s-])* | Match an optional opening parenthesis followed by three decimal digits, an optional closing parenthesis, and either a white-space character or a hyphen zero or one time. This is the first capturing group. | \d{3}=\d{4} | Match three decimal digits followed by a hyphen and four more decimal digits. | $ | Match the end of the input string. |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "^(\(*\d{3}\)*[\s-])*\d{3}-\d{4}$"
Dim inputs() As String = { "111 111-1111", "222-2222", "222 333-444", _
"(212) 111-1111", "111-AB1-1111", _
"212-111-1111", "01 999-9999" }
For Each input As String In inputs
If Regex.IsMatch(input, pattern) Then
Console.WriteLine(input + ": matched")
Else
Console.WriteLine(input + ": match failed")
End If
Next
End Sub
End Module
' The example displays the following output:
' 111 111-1111: matched
' 222-2222: matched
' 222 333-444: match failed
' (212) 111-1111: matched
' 111-AB1-1111: match failed
' 212-111-1111: matched
' 01 999-9999: match failed
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"^(\(*\d{3}\)*[\s-])*\d{3}-\d{4}$";
string[] inputs = { "111 111-1111", "222-2222", "222 333-444",
"(212) 111-1111", "111-AB1-1111",
"212-111-1111", "01 999-9999" };
foreach (string input in inputs)
{
if (Regex.IsMatch(input, pattern))
Console.WriteLine(input + ": matched");
else
Console.WriteLine(input + ": match failed");
}
}
}
// The example displays the following output:
// 111 111-1111: matched
// 222-2222: matched
// 222 333-444: match failed
// (212) 111-1111: matched
// 111-AB1-1111: match failed
// 212-111-1111: matched
// 01 999-9999: match failed
Back to Top

Non-Digit Character: \D
\D matches any non-digit character. It is equivalent to the \p{Nd} regular expression pattern. If ECMAScript-compliant behavior is specified, \D is equivalent to [^0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options. The following example illustrates the \D language element. It tests whether a string such as a part number consists of the appropriate combination of decimal and non-decimal characters. The regular expression pattern ^\D\d{1,5}\D*$ is defined as shown in the following table. Element | Description |
|---|
^ | Begin the match at the beginning of the input string. | \D | Match a non-digit character. | \d{1,5} | Match from one to five decimal digits. | \D* | Match zero or one non-decimal character. | $ | Match the end of the input string. |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "^\D\d{1,5}\D*$"
Dim inputs() As String = { "A1039C", "AA0001", "C18A", "Y938518" }
For Each input As String In inputs
If Regex.IsMatch(input, pattern) Then
Console.WriteLine(input + ": matched")
Else
Console.WriteLine(input + ": match failed")
End If
Next
End Sub
End Module
' The example displays the following output:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"^\D\d{1,5}\D*$";
string[] inputs = { "A1039C", "AA0001", "C18A", "Y938518" };
foreach (string input in inputs)
{
if (Regex.IsMatch(input, pattern))
Console.WriteLine(input + ": matched");
else
Console.WriteLine(input + ": match failed");
}
}
}
// The example displays the following output:
// A1039C: matched
// AA0001: match failed
// C18A: matched
// Y938518: match failed
Back to Top

Supported Unicode General Categories
Unicode defines the general categories listed in the following table. For more information, see the "UCD File Format" and "General Category Values" subtopics at the Unicode Character Database. Category | Description |
|---|
Lu | Letter, Uppercase | Ll | Letter, Lowercase | Lt | Letter, Titlecase | Lm | Letter, Modifier | Lo | Letter, Other | L | All letter characters. This includes the Lu, Ll, Lt, Lm, and Lo characters. | Mn | Mark, Nonspacing | Mc | Mark, Spacing Combining | Me | Mark, Enclosing | M | All diacritic marks. This includes the Mn, Mc, and Me categories. | Nd | Number, Decimal Digit | Nl | Number, Letter | No | Number, Other | N | All numbers. This includes the Nd, Nl, and No categories. | Pc | Punctuation, Connector | Pd | Punctuation, Dash | Ps | Punctuation, Open | Pe | Punctuation, Close | Pi | Punctuation, Initial quote (may behave like Ps or Pe depending on usage) | Pf | Punctuation, Final quote (may behave like Ps or Pe depending on usage) | Po | Punctuation, Other | P | All punctuation characters. This includes the Pc, Pd, Ps, Pe, Pi, Pf, and Po categories. | Sm | Symbol, Math | Sc | Symbol, Currency | Sk | Symbol, Modifier | So | Symbol, Other | S | All symbols. This includes the Sm, Sc, Sk, and So categories. | Zs | Separator, Space | Zl | Separator, Line | Zp | Separator, Paragraph | Z | All separator characters. This includes the Zs, Zl, and Zp categories. | Cc | Other, Control | Cf | Other, Format | Cs | Other, Surrogate | Co | Other, Private Use | Cn | Other, Not Assigned (no characters have this property) | C | All control characters. This includes the Cc, Cf, Cs, Co, and Cn categories. |
You can determine the Unicode category of any particular character by passing that character to the GetUnicodeCategory method. The following example uses the GetUnicodeCategory method to determine the category of each element in an array that contains selected Latin characters.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim chars() As Char = { "a"c, "X"c, "8"c, ","c, " "c, ChrW(9), "!"c }
For Each ch As Char In chars
Console.WriteLine("'{0}': {1}", Regex.Escape(ch.ToString()), _
Char.GetUnicodeCategory(ch))
Next
End Sub
End Module
' The example displays the following output:
' 'a': LowercaseLetter
' 'X': UppercaseLetter
' '8': DecimalDigitNumber
' ',': OtherPunctuation
' '\ ': SpaceSeparator
' '\t': Control
' '!': OtherPunctuation
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
char[] chars = { 'a', 'X', '8', ',', ' ', '\u0009', '!' };
foreach (char ch in chars)
Console.WriteLine("'{0}': {1}", Regex.Escape(ch.ToString()),
Char.GetUnicodeCategory(ch));
}
}
// The example displays the following output:
// 'a': LowercaseLetter
// 'X': UppercaseLetter
// '8': DecimalDigitNumber
// ',': OtherPunctuation
// '\ ': SpaceSeparator
// '\t': Control
// '!': OtherPunctuation
Back to Top

Supported Named Blocks
The .NET Framework provides the named blocks listed in the following table. The set of supported named blocks is based on Unicode 4.0 and Perl 5.6. Code point range | Block name |
|---|
0000 - 007F | IsBasicLatin | 0080 - 00FF | IsLatin-1Supplement | 0100 - 017F | IsLatinExtended-A | 0180 - 024F | IsLatinExtended-B | 0250 - 02AF | IsIPAExtensions | 02B0 - 02FF | IsSpacingModifierLetters | 0300 - 036F | IsCombiningDiacriticalMarks | 0370 - 03FF | IsGreek -or- IsGreekandCoptic | 0400 - 04FF | IsCyrillic | 0500 - 052F | IsCyrillicSupplement | 0530 - 058F | IsArmenian | 0590 - 05FF | IsHebrew | 0600 - 06FF | IsArabic | 0700 - 074F | IsSyriac | 0780 - 07BF | IsThaana | 0900 - 097F | IsDevanagari | 0980 - 09FF | IsBengali | 0A00 - 0A7F | IsGurmukhi | 0A80 - 0AFF | IsGujarati | 0B00 - 0B7F | IsOriya | 0B80 - 0BFF | IsTamil | 0C00 - 0C7F | IsTelugu | 0C80 - 0CFF | IsKannada | 0D00 - 0D7F | IsMalayalam | 0D80 - 0DFF | IsSinhala | 0E00 - 0E7F | IsThai | 0E80 - 0EFF | IsLao | 0F00 - 0FFF | IsTibetan | 1000 - 109F | IsMyanmar | 10A0 - 10FF | IsGeorgian | 1100 - 11FF | IsHangulJamo | 1200 - 137F | IsEthiopic | 13A0 - 13FF | IsCherokee | 1400 - 167F | IsUnifiedCanadianAboriginalSyllabics | 1680 - 169F | IsOgham | 16A0 - 16FF | IsRunic | 1700 - 171F | IsTagalog | 1720 - 173F | IsHanunoo | 1740 - 175F | IsBuhid | 1760 - 177F | IsTagbanwa | 1780 - 17FF | IsKhmer | 1800 - 18AF | IsMongolian | 1900 - 194F | IsLimbu | 1950 - 197F | IsTaiLe | 19E0 - 19FF | IsKhmerSymbols | 1D00 - 1D7F | IsPhoneticExtensions | 1E00 - 1EFF | IsLatinExtendedAdditional | 1F00 - 1FFF | IsGreekExtended | 2000 - 206F | IsGeneralPunctuation | 2070 - 209F | IsSuperscriptsandSubscripts | 20A0 - 20CF | IsCurrencySymbols | 20D0 - 20FF | IsCombiningDiacriticalMarksforSymbols -or- IsCombiningMarksforSymbols | 2100 - 214F | IsLetterlikeSymbols | 2150 - 218F | IsNumberForms | 2190 - 21FF | IsArrows | 2200 - 22FF | IsMathematicalOperators | 2300 - 23FF | IsMiscellaneousTechnical | 2400 - 243F | IsControlPictures | 2440 - 245F | IsOpticalCharacterRecognition | 2460 - 24FF | IsEnclosedAlphanumerics | 2500 - 257F | IsBoxDrawing | 2580 - 259F | IsBlockElements | 25A0 - 25FF | IsGeometricShapes | 2600 - 26FF | IsMiscellaneousSymbols | 2700 - 27BF | IsDingbats | 27C0 - 27EF | IsMiscellaneousMathematicalSymbols-A | 27F0 - 27FF | IsSupplementalArrows-A | 2800 - 28FF | IsBraillePatterns | 2900 - 297F | IsSupplementalArrows-B | 2980 - 29FF | IsMiscellaneousMathematicalSymbols-B | 2A00 - 2AFF | IsSupplementalMathematicalOperators | 2B00 - 2BFF | IsMiscellaneousSymbolsandArrows | 2E80 - 2EFF | IsCJKRadicalsSupplement | 2F00 - 2FDF | IsKangxiRadicals | 2FF0 - 2FFF | IsIdeographicDescriptionCharacters | 3000 - 303F | IsCJKSymbolsandPunctuation | 3040 - 309F | IsHiragana | 30A0 - 30FF | IsKatakana | 3100 - 312F | IsBopomofo | 3130 - 318F | IsHangulCompatibilityJamo | 3190 - 319F | IsKanbun | 31A0 - 31BF | IsBopomofoExtended | 31F0 - 31FF | IsKatakanaPhoneticExtensions | 3200 - 32FF | IsEnclosedCJKLettersandMonths | 3300 - 33FF | IsCJKCompatibility | 3400 - 4DBF | IsCJKUnifiedIdeographsExtensionA | 4DC0 - 4DFF | IsYijingHexagramSymbols | 4E00 - 9FFF | IsCJKUnifiedIdeographs | A000 - A48F | IsYiSyllables | A490 - A4CF | IsYiRadicals | AC00 - D7AF | IsHangulSyllables | D800 - DB7F | IsHighSurrogates | DB80 - DBFF | IsHighPrivateUseSurrogates | DC00 - DFFF | IsLowSurrogates | E000 - F8FF | IsPrivateUse or IsPrivateUseArea | F900 - FAFF | IsCJKCompatibilityIdeographs | FB00 - FB4F | IsAlphabeticPresentationForms | FB50 - FDFF | IsArabicPresentationForms-A | FE00 - FE0F | IsVariationSelectors | FE20 - FE2F | IsCombiningHalfMarks | FE30 - FE4F | IsCJKCompatibilityForms | FE50 - FE6F | IsSmallFormVariants | FE70 - FEFF | IsArabicPresentationForms-B | FF00 - FFEF | IsHalfwidthandFullwidthForms | FFF0 - FFFF | IsSpecials |
Back to Top

Character Class Subtraction
A character class defines a set of characters. Character class subtraction yields a set of characters that is the result of excluding the characters in one character class from another character class. A character class subtraction expression has the following form: [base_group-[excluded_group]] The square brackets ([]) and hyphen (-) are mandatory. The base_group is a positive or negative character group as described in the Character Class Syntax table. The excluded_group component is another positive or negative character group, or another character class subtraction expression (that is, you can nest character class subtraction expressions). For example, suppose you have a base group that consists of the character range from "a" through "z". To define the set of characters that consists of the base group except for the character "m", use [a-z-[m]]. To define the set of characters that consists of the base group except for the set of characters "d", "j", and "p", use [a-z-[djp]]. To define the set of characters that consists of the base group except for the character range from "m" through "p", use [a-z-[m-p]]. Consider the nested character class subtraction expression, [a-z-[d-w-[m-o]]]. The expression is evaluated from the innermost character range outward. First, the character range from "m" through "o" is subtracted from the character range "d" through "w", which yields the set of characters from "d" through "l" and "p" through "w". That set is then subtracted from the character range from "a" through "z", which yields the set of characters [abcmnoxyz]. You can use any character class with character class subtraction. To define the set of characters that consists of all Unicode characters from \u0000 through \uFFFF except white-space characters (\s), the characters in the punctuation general category (\p{P}), the characters in the IsGreek named block (\p{IsGreek}), and the Unicode NEXT LINE control character (\x85), use [\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]. Choose character classes for a character class subtraction expression that will yield useful results. Avoid an expression that yields an empty set of characters, which cannot match anything, or an expression that is equivalent to the original base group. For example, the empty set is the result of the expression [\p{IsBasicLatin}-[\x00-\x7F]], which subtracts all characters in the IsBasicLatin character range from the IsBasicLatin general category. Similarly, the original base group is the result of the expression [a-z-[0-9]]. This is because the base group, which is the character range of letters from "a" through "z", does not contain any characters in the excluded group, which is the character range of decimal digits from "0" through "9". The following example defines a regular expression, ^[0-9-[2468]]+$, that matches zero and odd digits in an input string. The regular expression is interpreted as shown in the following table. Element | Description |
|---|
^ | Begin the match at the start of the input string. | [0-9-[2468]]+ | Match one or more occurrences of any character from 0 to 9 except for 2, 4, 6, and 8. In other words, match one or more occurrences of zero or an odd digit. | $ | End the match at the end of the input string. |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim inputs() As String = { "123", "13579753", "3557798", "335599901" }
Dim pattern As String = "^[0-9-[2468]]+$"
For Each input As String In inputs
Dim match As Match = Regex.Match(input, pattern)
If match.Success Then Console.WriteLine(match.Value)
Next
End Sub
End Module
' The example displays the following output:
' 13579753
' 335599901
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string[] inputs = { "123", "13579753", "3557798", "335599901" };
string pattern = @"^[0-9-[2468]]+$";
foreach (string input in inputs)
{
Match match = Regex.Match(input, pattern);
if (match.Success)
Console.WriteLine(match.Value);
}
}
}
// The example displays the following output:
// 13579753
// 335599901
Back to Top

See Also
|
.NET Framework 4 文字クラス 文字クラスは、いずれかが入力文字列に含まれると一致と見なされる文字のセットを定義します。 .NET Framework の正規表現言語では、次の文字クラスがサポートされます。 文字グループの肯定。 入力文字列内の文字が指定した文字のセットのいずれかと一致する必要があります。 詳細については、「文字グループの肯定」を参照してください。 文字グループの否定。 入力文字列内の文字が指定した文字のセットのいずれかと一致しない必要があります。 詳細については、「文字グループの否定」を参照してください。 任意の文字。 正規表現の . (ドットまたはピリオド) 文字は、\n を除く任意の文字と一致するワイルドカード文字です。 詳細については、「任意の文字」を参照してください。 Unicode 一般カテゴリまたは名前付きブロック。 入力文字列内の文字が一致と見なされるには、その文字が特定の Unicode カテゴリのメンバーであるか、または Unicode 文字の連続した範囲内に含まれる必要があります。 詳細については、「Unicode カテゴリまたは Unicode ブロック」を参照してください。 Unicode 一般カテゴリまたは名前付きブロックの否定。 入力文字列内の文字が一致と見なされるには、その文字が特定の Unicode カテゴリのメンバーでないか、または Unicode 文字の連続した範囲内に含まれない必要があります。 詳細については、「Unicode カテゴリまたは Unicode ブロックの否定」を参照してください。 単語に使用される文字。 入力文字列内の文字が、単語内の文字に適した Unicode カテゴリのいずれかに属することができます。 詳細については、「単語に使用される文字」を参照してください。 単語に使用されない文字。 入力文字列内の文字が、単語に使用される文字ではない Unicode カテゴリのいずれかに属することができます。 詳細については、「単語に使用されない文字」を参照してください。 空白文字。 入力文字列内の文字が、Unicode 区切り記号および各種制御文字のいずれかです。 詳細については、「空白文字」を参照してください。 空白以外の文字。 入力文字列内の文字が、空白文字以外の文字のいずれかです。 詳細については、「空白以外の文字」を参照してください。 10 進数。 入力文字列内の文字が、Unicode 10 進数に分類される各種文字のいずれかです。 詳細については、「10 進数字」を参照してください。 10 進数字以外の文字。 入力文字列内の文字が、Unicode 10 進数以外の文字のいずれかです。 詳細については、「10 進数字」を参照してください。
.NET Framework は、文字クラスの減算式をサポートしています。これにより、ある文字クラスから別の文字クラスを除外した結果を文字のセットとして定義できます。 詳細については、「文字クラス減算」を参照してください。

文字グループの肯定: [ ]
文字グループの肯定では、いずれかが入力文字列に含まれると一致と見なされる文字の一覧を指定します。 この文字の一覧は、個別に指定されることも範囲として指定されることも、その両方であることもあります。 個別の文字の一覧を指定する構文は次のとおりです。 [character_group] ここで、character_group は、入力文字列に含まれると一致と見なされる個別の文字の一覧です。 character_group は、リテラル文字、エスケープ文字、または文字クラスを 1 つ以上組み合わせて構成されます。 文字の範囲を指定する構文は次のとおりです。
[firstCharacter-lastCharacter]
ここで、firstCharacter は範囲の最初の文字で、lastCharacter は範囲の最後の文字です。 文字範囲は連続する一連の文字で、範囲の最初の文字、ハイフン (-)、および範囲の最後の文字を指定することで定義されます。 2 つの文字の Unicode コード ポイントが隣接している場合、それらの文字は連続しています。 文字クラスの肯定を含む一般的な正規表現パターンをいくつか次の表に示します。 パターン | 説明 |
|---|
[aeiou] | すべての母音と一致します。 | [\p{P}\d] | すべての句読点および 10 進数字と一致します。 | [\s\p{P}] | すべての空白および句読点と一致します。 |
次の例では、"a" および "e" という文字を含む文字グループの肯定を定義し、入力文字列内で "grey" または "gray" という語の後に別の語が続くと一致と見なされるようにします。
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "gr[ae]y\s\S+?[\s|\p{P}]"
Dim input As String = "The gray wolf jumped over the grey wall."
Dim matches As MatchCollection = Regex.Matches(input, pattern)
For Each match As Match In matches
Console.WriteLine(match.Value)
Next
End Sub
End Module
' The example displays the following output:
' gray wolf
' grey wall.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"gr[ae]y\s\S+?[\s|\p{P}]";
string input = "The gray wolf jumped over the grey wall.";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
Console.WriteLine(match.Value);
}
}
// The example displays the following output:
// gray wolf
// grey wall.
正規表現 gr[ae]y\s\S+?[\s|\p{P}] は、次のように定義されています。 パターン | 説明 |
|---|
gr | リテラル文字 "gr" と一致します。 | [ae] | "a" または "e" と一致します。 | y\s | リテラル文字 "y" の後に空白文字が続く語と一致します。 | \S+? | 1 つ以上 (ただし、できるだけ少ない数) の空白以外の文字と一致します。 | [\s|\p{P}] | 空白文字または句読点と一致します。 |
次の例は、大文字で始まる語と一致します。 部分式 [A-Z] を使用して、A から Z の範囲の大文字を表します。
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b[A-Z]\w*\b"
Dim input As String = "A city Albany Zulu maritime Marseilles"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Value)
Next
End Sub
End Module
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b[A-Z]\w*\b";
string input = "A city Albany Zulu maritime Marseilles";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine(match.Value);
}
}
// The example displays the following output:
// A
// Albany
// Zulu
// Marseilles
正規表現 \b[A-Z]\w*\b は、次の表に示すように定義されています。 パターン | 説明 |
|---|
\b | ワード境界から開始します。 | [A-Z] | A から Z の任意の大文字と一致します。 | \w* | 0 個以上の単語に使用される文字に一致します。 | \b | ワード境界に一致します。 |
ページのトップへ

文字グループの否定: [^]
文字グループの否定では、入力文字列に含まれなければ一致と見なされる文字の一覧を指定します。 この文字の一覧は、個別に指定されることも範囲として指定されることも、その両方であることもあります。 個別の文字の一覧を指定する構文は次のとおりです。 [^character_group] ここで、character_group は、入力文字列に含まれなければ一致と見なされる個別の文字の一覧です。 character_group は、リテラル文字、エスケープ文字、または文字クラスを 1 つ以上組み合わせて構成されます。 文字の範囲を指定する構文は次のとおりです。 [^firstCharacter-lastCharacter] ここで、firstCharacter は範囲の最初の文字で、lastCharacter は範囲の最後の文字です。 文字範囲は連続する一連の文字で、範囲の最初の文字、ハイフン (-)、および範囲の最後の文字を指定することで定義されます。 2 つの文字の Unicode コード ポイントが隣接している場合、それらの文字は連続しています。 複数の文字範囲を連結することもできます。 たとえば、"0" ~ "9" の範囲の 10 進数、"a" ~ "f" の範囲の小文字、および "A" ~ "F" の範囲の大文字を指定するには、[0-9a-fA-F] を使用します。 文字グループの否定における先頭のキャレット文字 (^) は、文字グループが文字グループの肯定ではなく文字グループの否定であることを示し、省略できません。 重要 |
|---|
大規模な正規表現パターンにおける文字グループの否定は、ゼロ幅アサーションではありません。 つまり、正規表現エンジンは、文字グループの否定を評価した後に、入力文字列内で 1 文字進みます。 |
文字グループの否定を含む一般的な正規表現パターンをいくつか次の表に示します。 パターン | 説明 |
|---|
[^aeiou] | 母音を除くすべての文字と一致します。 | [^\p{P}\d] | 句読点および 10 進数字を除くすべての文字と一致します。 |
次の例は、"th" という文字で始まってその後に "o" が続かない語と一致します。
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\bth[^o]\w+\b"
Dim input As String = "thought thing though them through thus " + _
"thorough this"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Value)
Next
End Sub
End Module
' The example displays the following output:
' thing
' them
' through
' thus
' this
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\bth[^o]\w+\b";
string input = "thought thing though them through thus thorough this";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine(match.Value);
}
}
// The example displays the following output:
// thing
// them
// through
// thus
// this
正規表現 \bth[^o]\w+\b は、次の表に示すように定義されています。 パターン | 説明 |
|---|
\b | ワード境界から開始します。 | th | リテラル文字 "th" と一致します。 | [^o] | "o" 以外の任意の文字と一致します。 | \w+ | 1 つ以上の単語文字に一致します。 | \b | ワード境界で終了します。 |
ページのトップへ

任意の文字: .
ピリオド文字 (.) は、\n (改行文字、\u000A) を除く任意の文字と一致しますが、次の 2 つの制限があります。 正規表現パターンが RegexOptions..::.Singleline オプションで修飾されている場合、または . 文字クラスを含むパターンの一部が s オプションで修飾されている場合は、. は任意の文字と一致します。 詳細については、「正規表現のオプション」を参照してください。 . 文字クラスの既定の動作と RegexOptions..::.Singleline オプションが指定されている場合の動作の違いの例を次に示します。 正規表現 ^.+ は文字列の先頭から開始し、すべての文字と一致します。 既定では、照合は 1 行目の末尾で終了します。正規表現パターンは復帰文字 \r (\u000D) と一致しますが、\n とは一致しません。 RegexOptions..::.Singleline オプションは入力文字列全体を単一行として解釈するので、\n を含む入力文字列内のすべての文字と一致します。
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "^.+"
Dim input As String = "This is one line and" + vbCrLf + "this is the second."
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(Regex.Escape(match.Value))
Next
Console.WriteLine()
For Each match As Match In Regex.Matches(input, pattern, RegexOptions.SingleLine)
Console.WriteLine(Regex.Escape(match.Value))
Next
End Sub
End Module
' The example displays the following output:
' This\ is\ one\ line\ and\r
'
' This\ is\ one\ line\ and\r\nthis\ is\ the\ second\.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = "^.+";
string input = "This is one line and" + Environment.NewLine + "this is the second.";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine(Regex.Escape(match.Value));
Console.WriteLine();
foreach (Match match in Regex.Matches(input, pattern, RegexOptions.Singleline))
Console.WriteLine(Regex.Escape(match.Value));
}
}
// The example displays the following output:
// This\ is\ one\ line\ and\r
//
// This\ is\ one\ line\ and\r\nthis\ is\ the\ second\.
メモ |
|---|
. 文字クラスは \n を除く任意の文字と一致するので、このクラスも \r (復帰文字、\u000D) と一致します。 |
メモ |
|---|
. 言語要素は任意の文字と一致するので、正規表現パターンが任意の文字と複数回一致する場合に最短一致の量指定子と共によく使用されます。 詳細については、「量指定子」を参照してください。 |
ページのトップへ

Unicode カテゴリまたは Unicode ブロック: \p{}
Unicode 規格では、各文字に一般カテゴリが割り当てられています。 たとえば、特定の文字は、英大文字 (Lu カテゴリで表されます)、10 進数 (Nd カテゴリ)、数学記号 (Sm カテゴリ)、または段落区切り記号 (Zl カテゴリ) に分類できます。 また、Unicode 規格の特定の文字セットは、特定の範囲またはブロックの連続したコード ポイントに対応します。 たとえば、基本的なラテン語文字セットは \u0000 ~ \u007F で、アラビア語文字セットは \u0600 ~ \u06FF です。 正規表現の構成要素 \p{name} は、Unicode 一般カテゴリまたは名前付きブロックに属する任意の文字と一致します。ここで、name はカテゴリの省略形または名前付きブロックの名前です。 カテゴリの省略形の一覧については、このトピックで後述する「サポートされている Unicode 一般カテゴリ」を参照してください。 名前付きブロックの一覧については、このトピックで後述する「サポートされている名前付きブロック」を参照してください。 \p{name} 構成要素を使用して Unicode 一般カテゴリ (この場合は Pd (Punctuation, Dash: 句読点、ダッシュ) カテゴリ) と名前付きブロック (IsGreek 名前付きブロックおよび IsBasicLatin 名前付きブロック) の両方を照合する例を次に示します。
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+"
Dim input As String = "Κατα Μαθθαίον - The Gospel of Matthew"
Console.WriteLine(Regex.IsMatch(input, pattern)) ' Displays True.
End Sub
End Module
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+";
string input = "Κατα Μαθθαίον - The Gospel of Matthew";
Console.WriteLine(Regex.IsMatch(input, pattern)); // Displays True.
}
}
正規表現 \b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+ は、次の表に示すように定義されています。 パターン | 説明 |
|---|
\b | ワード境界から開始します。 | \p{IsGreek}+ | 1 つ以上のギリシャ文字と一致します。 | (\s)? | 0 個または 1 個の空白文字と一致します。 | (\p{IsGreek}+(\s)?)+ | 1 つ以上のギリシャ文字の後に 0 個または 1 個の空白文字が 1 回以上続くパターンに一致します。 | \p{Pd} | Punctuation, Dash (句読点、ダッシュ) 文字と一致します。 | \s | 空白文字と一致します。 | \p{IsBasicLatin}+ | 1 つ以上の基本的なラテン文字と一致します。 | (\s)? | 0 個または 1 個の空白文字と一致します。 | (\p{IsBasicLatin}+(\s)?)+ | 1 つ以上の基本的なラテン文字の後に 0 個または 1 個の空白文字が 1 回以上続くパターンに一致します。 |
ページのトップへ

Unicode カテゴリまたは Unicode ブロックの否定: \P{}
Unicode 規格では、各文字に一般カテゴリが割り当てられています。 たとえば、特定の文字は、英大文字 (Lu カテゴリで表されます)、10 進数 (Nd カテゴリ)、数学記号 (Sm カテゴリ)、または段落区切り記号 (Zl カテゴリ) に分類できます。 また、Unicode 規格の特定の文字セットは、特定の範囲またはブロックの連続したコード ポイントに対応します。 たとえば、基本的なラテン語文字セットは \u0000 ~ \u007F で、アラビア語文字セットは \u0600 ~ \u06FF です。 正規表現の構成要素 \P{name} は、Unicode 一般カテゴリまたは名前付きブロックに属さない任意の文字と一致します。ここで、name はカテゴリの省略形または名前付きブロックの名前です。 カテゴリの省略形の一覧については、このトピックで後述する「サポートされている Unicode 一般カテゴリ」を参照してください。 名前付きブロックの一覧については、このトピックで後述する「サポートされている名前付きブロック」を参照してください。 \P{name} 構成要素を使用して通貨記号 (この場合は Sc (Symbol, Currency: 記号、通貨) カテゴリ) を数値文字列から除外する例を次に示します。
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "(\P{Sc})+"
Dim values() As String = { "$164,091.78", "£1,073,142.68", "73¢", "€120"}
For Each value As String In values
Console.WriteLine(Regex.Match(value, pattern).Value)
Next
End Sub
End Module
' The example displays the following output:
' 164,091.78
' 1,073,142.68
' 73
' 120
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"(\P{Sc})+";
string[] values = { "$164,091.78", "£1,073,142.68", "73¢", "€120" };
foreach (string value in values)
Console.WriteLine(Regex.Match(value, pattern).Value);
}
}
// The example displays the following output:
// 164,091.78
// 1,073,142.68
// 73
// 120
正規表現パターン (\P{Sc})+ は、通貨記号以外の 1 つ以上の文字と一致し、結果文字列から通貨記号を効果的に除外します。 ページのトップへ

単語に使用される文字: \w
\w は、単語に使用される任意の文字と一致します。 単語に使用される文字は、次の表に示す Unicode カテゴリのメンバーです。 カテゴリ | 説明 |
|---|
Ll | Letter, Lowercase (字、小文字) | Lu | Letter, Uppercase (字、大文字) | Lt | Letter, Titlecase (字、タイトル文字) | Lo | Letter, Other (字、その他) | Lm | Letter, Modifier (字、修飾) | Nd | Number, Decimal Digit (数、10 進数字) | Pc | Punctuation, Connector (句読点、接続)。 このカテゴリには 10 文字が含まれ、そのうち最もよく使用される文字は LOWLINE 文字 (_)、u+005F です。 |
ECMAScript 準拠の動作が指定された場合、\w は [a-zA-Z_0-9] と同じになります。 ECMAScript 正規表現の詳細については、「正規表現のオプション」の「ECMAScript 一致の動作」のセクションを参照してください。 メモ |
|---|
\w 言語要素は単語に使用される任意の文字と一致するので、正規表現パターンが単語に使用される任意の文字の後に特定の単語に使用される文字が続く語と複数回一致する場合に最短一致の量指定子と共によく使用されます。 詳細については、「量指定子」を参照してください。 |
\w 言語要素を使用して単語内の重複する文字を照合する例を次に示します。 この例では、次のように解釈できる正規表現パターン (\w)\1 を定義しています。 要素 | 説明 |
|---|
(\w) | 単語に使用される文字と一致します。 これが最初のキャプチャ グループです。 | \1 | 最初のキャプチャの値と一致します。 |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "(\w)\1"
Dim words() As String = { "trellis", "seer", "latter", "summer", _
"hoarse", "lesser", "aardvark", "stunned" }
For Each word As String In words
Dim match As Match = Regex.Match(word, pattern)
If match.Success Then
Console.WriteLine("'{0}' found in '{1}' at position {2}.", _
match.Value, word, match.Index)
Else
Console.WriteLine("No double characters in '{0}'.", word)
End If
Next
End Sub
End Module
' The example displays the following output:
' 'll' found in 'trellis' at position 3.
' 'ee' found in 'seer' at position 1.
' 'tt' found in 'latter' at position 2.
' 'mm' found in 'summer' at position 2.
' No double characters in 'hoarse'.
' 'ss' found in 'lesser' at position 2.
' 'aa' found in 'aardvark' at position 0.
' 'nn' found in 'stunned' at position 3.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"(\w)\1";
string[] words = { "trellis", "seer", "latter", "summer",
"hoarse", "lesser", "aardvark", "stunned" };
foreach (string word in words)
{
Match match = Regex.Match(word, pattern);
if (match.Success)
Console.WriteLine("'{0}' found in '{1}' at position {2}.",
match.Value, word, match.Index);
else
Console.WriteLine("No double characters in '{0}'.", word);
}
}
}
// The example displays the following output:
// 'll' found in 'trellis' at position 3.
// 'ee' found in 'seer' at position 1.
// 'tt' found in 'latter' at position 2.
// 'mm' found in 'summer' at position 2.
// No double characters in 'hoarse'.
// 'ss' found in 'lesser' at position 2.
// 'aa' found in 'aardvark' at position 0.
// 'nn' found in 'stunned' at position 3.
ページのトップへ

単語に使用されない文字: \W
\W は、単語に使用される文字以外の任意の文字と一致します。 \W 言語要素は、次の文字クラスと同じ結果をもたらします。
[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}]
つまり、次の表に示す文字を除く任意の文字と一致します。 カテゴリ | 説明 |
|---|
Ll | Letter, Lowercase (字、小文字) | Lu | Letter, Uppercase (字、大文字) | Lt | Letter, Titlecase (字、タイトル文字) | Lo | Letter, Other (字、その他) | Lm | Letter, Modifier (字、修飾) | Nd | Number, Decimal Digit (数、10 進数字) | Pc | Punctuation, Connector (句読点、接続)。 このカテゴリには 10 文字が含まれ、そのうち最もよく使用される文字は LOWLINE 文字 (_)、u+005F です。 |
ECMAScript 準拠の動作が指定された場合、\W は [^a-zA-Z_0-9] と同じになります。 ECMAScript 正規表現の詳細については、「正規表現のオプション」の「ECMAScript 一致の動作」のセクションを参照してください。 メモ |
|---|
\W 言語要素は単語に使用されない任意の文字と一致するので、正規表現パターンが単語に使用されない任意の文字の後に特定の単語に使用されない文字が続く語と複数回一致する場合に最短一致の量指定子と共によく使用されます。 詳細については、「量指定子」を参照してください。 |
\w 文字クラスの例を次に示します。 この例では、単語の後に 1 つ以上の単語に使用されない文字 (空白や句読点など) が続く場合に一致する正規表現パターン \b(\w+)(\W){1,2} を定義しています。 この正規表現の解釈を次の表に示します。 要素 | 説明 |
|---|
\b | ワード境界から照合を開始します。 | (\w+) | 1 つ以上の単語文字に一致します。 これが最初のキャプチャ グループです。 | (\w){1,2} | 単語に使用されない文字と 1 回または 2 回一致します。 これが 2 番目のキャプチャ グループです。 |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b(\w+)(\W){1,2}"
Dim input As String = "The old, grey mare slowly walked across the narrow, green pasture."
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Value)
Console.Write(" Non-word character(s):")
Dim captures As CaptureCollection = match.Groups(2).Captures
For ctr As Integer = 0 To captures.Count - 1
Console.Write("'{0}' (\u{1}){2}", captures(ctr).Value, _
Convert.ToUInt16(captures(ctr).Value.Chars(0)).ToString("X4"), _
If(ctr < captures.Count - 1, ", ", ""))
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' The
' Non-word character(s):' ' (\u0020)
' old,
' Non-word character(s):',' (\u002C), ' ' (\u0020)
' grey
' Non-word character(s):' ' (\u0020)
' mare
' Non-word character(s):' ' (\u0020)
' slowly
' Non-word character(s):' ' (\u0020)
' walked
' Non-word character(s):' ' (\u0020)
' across
' Non-word character(s):' ' (\u0020)
' the
' Non-word character(s):' ' (\u0020)
' narrow,
' Non-word character(s):',' (\u002C), ' ' (\u0020)
' green
' Non-word character(s):' ' (\u0020)
' pasture.
' Non-word character(s):'.' (\u002E)
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b(\w+)(\W){1,2}";
string input = "The old, grey mare slowly walked across the narrow, green pasture.";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
Console.Write(" Non-word character(s):");
CaptureCollection captures = match.Groups[2].Captures;
for (int ctr = 0; ctr < captures.Count; ctr++)
Console.Write(@"'{0}' (\u{1}){2}", captures[ctr].Value,
Convert.ToUInt16(captures[ctr].Value[0]).ToString("X4"),
ctr < captures.Count - 1 ? ", " : "");
Console.WriteLine();
}
}
}
// The example displays the following output:
// The
// Non-word character(s):' ' (\u0020)
// old,
// Non-word character(s):',' (\u002C), ' ' (\u0020)
// grey
// Non-word character(s):' ' (\u0020)
// mare
// Non-word character(s):' ' (\u0020)
// slowly
// Non-word character(s):' ' (\u0020)
// walked
// Non-word character(s):' ' (\u0020)
// across
// Non-word character(s):' ' (\u0020)
// the
// Non-word character(s):' ' (\u0020)
// narrow,
// Non-word character(s):',' (\u002C), ' ' (\u0020)
// green
// Non-word character(s):' ' (\u0020)
// pasture.
// Non-word character(s):'.' (\u002E)
2 番目のキャプチャ グループの Group オブジェクトには、キャプチャされた単語に使用されない文字が 1 つだけ含まれるので、この例では、Group..::.Captures プロパティによって返される CaptureCollection オブジェクトから、キャプチャされたすべての単語に使用されない文字を取得します。 ページのトップへ

空白文字: \s
\s は、空白文字と一致します。 次の表に示すエスケープ シーケンスおよび Unicode カテゴリと同じ結果をもたらします。 カテゴリ | 説明 |
|---|
\f | フォーム フィード文字 (\u000C)。 | \n | 改行文字 (\u000A)。 | \r | 復帰文字 (\u000D)。 | \t | タブ文字 (\u0009)。 | \v | 垂直タブ文字 (\u000B)。 | \x85 | 省略記号または NEXT LINE (NEL) 文字 (…) (\u0085)。 | \p{Z} | 任意の区切り記号と一致します。 |
ECMAScript 準拠の動作が指定された場合、\s は [\f\n\r\t\v] と同じになります。 ECMAScript 正規表現の詳細については、「正規表現のオプション」の「ECMAScript 一致の動作」のセクションを参照してください。 \s 文字クラスの例を次に示します。 この例では、"s" または "es" で終わる単語の後に空白文字または入力文字列の末尾が続く場合に一致する正規表現パターン \b\w+(e)*s(\s|$) を定義しています。 この正規表現の解釈を次の表に示します。 要素 | 説明 |
|---|
\b | ワード境界から照合を開始します。 | \w+ | 1 つ以上の単語文字に一致します。 | (e)* | "e" と 0 回または 1 回一致します。 | s | "s" と一致します。 | (\s|$) | 空白文字または入力文字列の末尾と一致します。 |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b\w+(e)*s(\s|$)"
Dim input As String = "matches stores stops leave leaves"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Value)
Next
End Sub
End Module
' The example displays the following output:
' matches
' stores
' stops
' leaves
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b\w+(e)*s(\s|$)";
string input = "matches stores stops leave leaves";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine(match.Value);
}
}
// The example displays the following output:
// matches
// stores
// stops
// leaves
ページのトップへ

空白以外の文字: \S
\S は、空白文字以外の任意の文字と一致します。 [^\f\n\r\t\v\x85\p{Z}] 正規表現パターン、または空白文字と一致する \s に相当する正規表現パターンの逆と同じ結果をもたらします。 詳細については、「空白文字: \s」を参照してください。 ECMAScript 準拠の動作が指定された場合、\S は [^ \f\n\r\t\v] と同じになります。 ECMAScript 正規表現の詳細については、「正規表現のオプション」の「ECMAScript 一致の動作」のセクションを参照してください。 \S 言語要素の例を次に示します。 正規表現パターン \b(\S+)\s* は、空白文字で区切られた文字列と一致します。 一致部分の GroupCollection オブジェクトの 2 番目の要素に一致する文字列が含まれます。 この正規表現の解釈を次の表に示します。 要素 | 説明 |
|---|
\b | ワード境界から照合を開始します。 | (\S+) | 1 つ以上の空白以外の文字と一致します。 これが最初のキャプチャ グループです。 | \s* | 0 個または 1 個の空白文字と一致します。 |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "\b(\S+)\s*"
Dim input As String = "This is the first sentence of the first paragraph. " + _
"This is the second sentence." + vbCrLf + _
"This is the only sentence of the second paragraph."
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine(match.Groups(1))
Next
End Sub
End Module
' The example displays the following output:
' This
' is
' the
' first
' sentence
' of
' the
' first
' paragraph.
' This
' is
' the
' second
' sentence.
' This
' is
' the
' only
' sentence
' of
' the
' second
' paragraph.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\b(\S+)\s*";
string input = "This is the first sentence of the first paragraph. " +
"This is the second sentence.\n" +
"This is the only sentence of the second paragraph.";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine(match.Groups[1]);
}
}
// The example displays the following output:
// This
// is
// the
// first
// sentence
// of
// the
// first
// paragraph.
// This
// is
// the
// second
// sentence.
// This
// is
// the
// only
// sentence
// of
// the
// second
// paragraph.
ページのトップへ

10 進数字: \d
\d は、10 進数字と一致します。 標準の 10 進数 0 ~ 9 およびその他の各種文字セットの 10 進数を含む \p{Nd} 正規表現パターンと同じ結果をもたらします。 ECMAScript 準拠の動作が指定された場合、\d は [0-9] と同じになります。 ECMAScript 正規表現の詳細については、「正規表現のオプション」の「ECMAScript 一致の動作」のセクションを参照してください。 \d 言語要素の例を次に示します。 この例では、入力文字列が米国およびカナダの有効な電話番号を表すかどうかをテストします。 正規表現パターン ^(\(*\d{3}\)*[\s-])*\d{3}-\d{4}$ は、次の表に示すように定義されています。 要素 | 説明 |
|---|
^ | 入力文字列の先頭から照合を開始します。 | \(* | 0 個または 1 個のリテラル "(" 文字と一致します。 | \d{3} | 3 個の 10 進数と一致します。 | \)* | 0 個または 1 個のリテラル ")" 文字と一致します。 | [\s-] | ハイフンまたは空白文字と一致します。 | (\(*\d{3}\)*[\s-])* | 省略可能な左かっこの後に 3 個の 10 進数が続く部分、省略可能な右かっこ、および空白文字またはハイフンと 0 回または 1 回一致します。 これが最初のキャプチャ グループです。 | \d{3}=\d{4} | 3 個の 10 進数の後にハイフンおよび 4 個以上の 10 進数が続く場合に一致します。 | $ | 入力文字列の末尾と一致します。 |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "^(\(*\d{3}\)*[\s-])*\d{3}-\d{4}$"
Dim inputs() As String = { "111 111-1111", "222-2222", "222 333-444", _
"(212) 111-1111", "111-AB1-1111", _
"212-111-1111", "01 999-9999" }
For Each input As String In inputs
If Regex.IsMatch(input, pattern) Then
Console.WriteLine(input + ": matched")
Else
Console.WriteLine(input + ": match failed")
End If
Next
End Sub
End Module
' The example displays the following output:
' 111 111-1111: matched
' 222-2222: matched
' 222 333-444: match failed
' (212) 111-1111: matched
' 111-AB1-1111: match failed
' 212-111-1111: matched
' 01 999-9999: match failed
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"^(\(*\d{3}\)*[\s-])*\d{3}-\d{4}$";
string[] inputs = { "111 111-1111", "222-2222", "222 333-444",
"(212) 111-1111", "111-AB1-1111",
"212-111-1111", "01 999-9999" };
foreach (string input in inputs)
{
if (Regex.IsMatch(input, pattern))
Console.WriteLine(input + ": matched");
else
Console.WriteLine(input + ": match failed");
}
}
}
// The example displays the following output:
// 111 111-1111: matched
// 222-2222: matched
// 222 333-444: match failed
// (212) 111-1111: matched
// 111-AB1-1111: match failed
// 212-111-1111: matched
// 01 999-9999: match failed
ページのトップへ

数字以外の文字: \D
\D は、数字以外と一致します。 \p{Nd} 正規表現パターンと同じ結果をもたらします。 ECMAScript 準拠の動作が指定された場合、\D は [^0-9] と同じになります。 ECMAScript 正規表現の詳細については、「正規表現のオプション」の「ECMAScript 一致の動作」のセクションを参照してください。 \D 言語要素の例を次に示します。 部品番号などの文字列が 10 進数および 10 進数以外の文字を適切に組み合わせて構成されているかどうかをテストします。 正規表現パターン ^\D\d{1,5}\D*$ は、次の表に示すように定義されています。 要素 | 説明 |
|---|
^ | 入力文字列の先頭から照合を開始します。 | \D | 数字以外の文字と一致します。 | \d{1,5} | 1 ~ 5 個の 10 進数と一致します。 | \D* | 0 個または 1 個の 10 進数以外の文字と一致します。 | $ | 入力文字列の末尾と一致します。 |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "^\D\d{1,5}\D*$"
Dim inputs() As String = { "A1039C", "AA0001", "C18A", "Y938518" }
For Each input As String In inputs
If Regex.IsMatch(input, pattern) Then
Console.WriteLine(input + ": matched")
Else
Console.WriteLine(input + ": match failed")
End If
Next
End Sub
End Module
' The example displays the following output:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"^\D\d{1,5}\D*$";
string[] inputs = { "A1039C", "AA0001", "C18A", "Y938518" };
foreach (string input in inputs)
{
if (Regex.IsMatch(input, pattern))
Console.WriteLine(input + ": matched");
else
Console.WriteLine(input + ": match failed");
}
}
}
// The example displays the following output:
// A1039C: matched
// AA0001: match failed
// C18A: matched
// Y938518: match failed
ページのトップへ

サポートされている Unicode 一般カテゴリ
Unicode は、次の表に示されている一般カテゴリを定義しています。 詳細については、「Unicode Character Database」内の「UCD File Format」および「General Category Values」を参照してください。 カテゴリ | 説明 |
|---|
Lu | Letter, Uppercase (字、大文字) | Ll | Letter, Lowercase (字、小文字) | Lt | Letter, Titlecase (字、タイトル文字) | Lm | Letter, Modifier (字、修飾) | Lo | Letter, Other (字、その他) | L | すべてのアルファベット文字。 これには、Lu、Ll、Lt、Lm、および Lo の各文字が含まれます。 | Mn | Mark, Nonspacing (結合文字、幅なし) | Mc | Mark, Spacing Combining (結合文字、幅あり) | Me | Mark, Enclosing (結合文字、囲み) | M | すべての分音記号。 これには、Mn、Mc、および Me の各カテゴリが含まれます。 | Nd | Number, Decimal Digit (数、10 進数字) | Nl | Number, Letter (数、字) | No | Number, Other (数、その他) | N | すべての数。 これには、Nd、Nl、および No の各カテゴリが含まれます。 | Pc | Punctuation, Connector (句読点、接続) | Pd | Punctuation, Dash (句読点、ダッシュ) | Ps | Punctuation, Open (句読点、開き) | Pe | Punctuation, Close (句読点、閉じ) | Pi | Punctuation, Initial quote (句読点、開始引用符。使用状況に応じて Ps または Pe のように動作) | Pf | Punctuation, Final quote (句読点、終了引用符。使用状況に応じて Ps または Pe のように動作) | Po | Punctuation, Other (句読点、その他) | P | すべての句読点。 これには、Pc、Pd、Ps、Pe、Pi、Pf、および Po の各カテゴリが含まれます。 | Sm | Symbol, Math (記号、数学) | Sc | Symbol, Currency (記号、通貨) | Sk | Symbol, Modifier (記号、修飾) | So | Symbol, Other (記号、その他) | S | すべての記号。 これには、Sm、Sc、Sk、および So の各カテゴリが含まれます。 | Zs | Separator, Space (区切り、空白) | Zl | Separator, Line (区切り、行) | Zp | Separator, Paragraph (区切り、段落) | Z | すべての区切り記号。 これには、Zs、Zl、および Zp の各カテゴリが含まれます。 | Cc | Other, Control (区切り、制御) | Cf | Other, Format (その他、書式) | Cs | Other, Surrogate (その他、サロゲート) | Co | Other, Private Use (その他、プライベート用途) | Cn | Other, Not Assigned (その他、未割り当て。このプロパティを持つ文字はありません) | C | すべての制御文字。 これには、Cc、Cf、Cs、Co、および Cn の各カテゴリが含まれます。 |
特定の文字の Unicode カテゴリを確認するには、その文字を GetUnicodeCategory メソッドに渡します。 GetUnicodeCategory メソッドを使用して、選択したラテン文字を含む配列の各要素のカテゴリを確認する例を次に示します。
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim chars() As Char = { "a"c, "X"c, "8"c, ","c, " "c, ChrW(9), "!"c }
For Each ch As Char In chars
Console.WriteLine("'{0}': {1}", Regex.Escape(ch.ToString()), _
Char.GetUnicodeCategory(ch))
Next
End Sub
End Module
' The example displays the following output:
' 'a': LowercaseLetter
' 'X': UppercaseLetter
' '8': DecimalDigitNumber
' ',': OtherPunctuation
' '\ ': SpaceSeparator
' '\t': Control
' '!': OtherPunctuation
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
char[] chars = { 'a', 'X', '8', ',', ' ', '\u0009', '!' };
foreach (char ch in chars)
Console.WriteLine("'{0}': {1}", Regex.Escape(ch.ToString()),
Char.GetUnicodeCategory(ch));
}
}
// The example displays the following output:
// 'a': LowercaseLetter
// 'X': UppercaseLetter
// '8': DecimalDigitNumber
// ',': OtherPunctuation
// '\ ': SpaceSeparator
// '\t': Control
// '!': OtherPunctuation
ページのトップへ

サポートされている名前付きブロック
.NET Framework には、次の表に示す名前付きブロックが用意されています。 サポートされている一連の名前付きブロックは、Unicode 4.0 および Perl 5.6 に基づいています。 コード ポイント範囲 | ブロック名 |
|---|
0000 ~ 007F | IsBasicLatin | 0080 ~ 00FF | IsLatin-1Supplement | 0100 ~ 017F | IsLatinExtended-A | 0180 ~ 024F | IsLatinExtended-B | 0250 ~ 02AF | IsIPAExtensions | 02B0 ~ 02FF | IsSpacingModifierLetters | 0300 ~ 036F | IsCombiningDiacriticalMarks | 0370 ~ 03FF | IsGreek または IsGreekandCoptic | 0400 ~ 04FF | IsCyrillic | 0500 ~ 052F | IsCyrillicSupplement | 0530 ~ 058F | IsArmenian | 0590 ~ 05FF | IsHebrew | 0600 ~ 06FF | IsArabic | 0700 ~ 074F | IsSyriac | 0780 ~ 07BF | IsThaana | 0900 ~ 097F | IsDevanagari | 0980 ~ 09FF | IsBengali | 0A00 ~ 0A7F | IsGurmukhi | 0A80 ~ 0AFF | IsGujarati | 0B00 ~ 0B7F | IsOriya | 0B80 ~ 0BFF | IsTamil | 0C00 ~ 0C7F | IsTelugu | 0C80 ~ 0CFF | IsKannada | 0D00 ~ 0D7F | IsMalayalam | 0D80 ~ 0DFF | IsSinhala | 0E00 ~ 0E7F | IsThai | 0E80 ~ 0EFF | IsLao | 0F00 ~ 0FFF | IsTibetan | 1000 ~ 109F | IsMyanmar | 10A0 ~ 10FF | IsGeorgian | 1100 ~ 11FF | IsHangulJamo | 1200 ~ 137F | IsEthiopic | 13A0 ~ 13FF | IsCherokee | 1400 ~ 167F | IsUnifiedCanadianAboriginalSyllabics | 1680 ~ 169F | IsOgham | 16A0 ~ 16FF | IsRunic | 1700 ~ 171F | IsTagalog | 1720 ~ 173F | IsHanunoo | 1740 ~ 175F | IsBuhid | 1760 ~ 177F | IsTagbanwa | 1780 ~ 17FF | IsKhmer | 1800 ~ 18AF | IsMongolian | 1900 ~ 194F | IsLimbu | 1950 ~ 197F | IsTaiLe | 19E0 ~ 19FF | IsKhmerSymbols | 1D00 ~ 1D7F | IsPhoneticExtensions | 1E00 ~ 1EFF | IsLatinExtendedAdditional | 1F00 ~ 1FFF | IsGreekExtended | 2000 ~ 206F | IsGeneralPunctuation | 2070 ~ 209F | IsSuperscriptsandSubscripts | 20A0 ~ 20CF | IsCurrencySymbols | 20D0 ~ 20FF | IsCombiningDiacriticalMarksforSymbols または IsCombiningMarksforSymbols | 2100 ~ 214F | IsLetterlikeSymbols | 2150 ~ 218F | IsNumberForms | 2190 ~ 21FF | IsArrows | 2200 ~ 22FF | IsMathematicalOperators | 2300 ~ 23FF | IsMiscellaneousTechnical | 2400 ~ 243F | IsControlPictures | 2440 ~ 245F | IsOpticalCharacterRecognition | 2460 ~ 24FF | IsEnclosedAlphanumerics | 2500 ~ 257F | IsBoxDrawing | 2580 ~ 259F | IsBlockElements | 25A0 ~ 25FF | IsGeometricShapes | 2600 ~ 26FF | IsMiscellaneousSymbols | 2700 ~ 27BF | IsDingbats | 27C0 ~ 27EF | IsMiscellaneousMathematicalSymbols-A | 27F0 ~ 27FF | IsSupplementalArrows-A | 2800 ~ 28FF | IsBraillePatterns | 2900 ~ 297F | IsSupplementalArrows-B | 2980 ~ 29FF | IsMiscellaneousMathematicalSymbols-B | 2A00 ~ 2AFF | IsSupplementalMathematicalOperators | 2B00 ~ 2BFF | IsMiscellaneousSymbolsandArrows | 2E80 ~ 2EFF | IsCJKRadicalsSupplement | 2F00 ~ 2FDF | IsKangxiRadicals | 2FF0 ~ 2FFF | IsIdeographicDescriptionCharacters | 3000 ~ 303F | IsCJKSymbolsandPunctuation | 3040 ~ 309F | IsHiragana | 30A0 ~ 30FF | IsKatakana | 3100 ~ 312F | IsBopomofo | 3130 ~ 318F | IsHangulCompatibilityJamo | 3190 ~ 319F | IsKanbun | 31A0 ~ 31BF | IsBopomofoExtended | 31F0 ~ 31FF | IsKatakanaPhoneticExtensions | 3200 ~ 32FF | IsEnclosedCJKLettersandMonths | 3300 ~ 33FF | IsCJKCompatibility | 3400 ~ 4DBF | IsCJKUnifiedIdeographsExtensionA | 4DC0 ~ 4DFF | IsYijingHexagramSymbols | 4E00 ~ 9FFF | IsCJKUnifiedIdeographs | A000 ~ A48F | IsYiSyllables | A490 ~ A4CF | IsYiRadicals | AC00 ~ D7AF | IsHangulSyllables | D800 ~ DB7F | IsHighSurrogates | DB80 ~ DBFF | IsHighPrivateUseSurrogates | DC00 ~ DFFF | IsLowSurrogates | E000 ~ F8FF | IsPrivateUse または IsPrivateUseArea | F900 ~ FAFF | IsCJKCompatibilityIdeographs | FB00 ~ FB4F | IsAlphabeticPresentationForms | FB50 ~ FDFF | IsArabicPresentationForms-A | FE00 ~ FE0F | IsVariationSelectors | FE20 ~ FE2F | IsCombiningHalfMarks | FE30 ~ FE4F | IsCJKCompatibilityForms | FE50 ~ FE6F | IsSmallFormVariants | FE70 ~ FEFF | IsArabicPresentationForms-B | FF00 ~ FFEF | IsHalfwidthandFullwidthForms | FFF0 ~ FFFF | IsSpecials |
ページのトップへ

文字クラス減算
文字クラスは、文字のセットを定義します。 文字クラス減算によって、ある文字クラスから別の文字クラスの文字を除外した文字セットが生成されます。 文字クラス減算式の形式は次のとおりです。 [base_group-[excluded_group]] 角かっこ ([]) とハイフン (-) は省略できません。 base_group は、「文字クラスの構文」の表で説明されている文字グループの肯定または文字グループの否定です。 excluded_group は、別の文字グループの肯定または文字グループの否定、あるいは別の文字クラス減算式です (つまり文字クラス減算式は入れ子にできます)。 たとえば、"a" ~ "z" の文字範囲で構成される基本グループがあるとします。 "m" を除外した基本グループで構成される文字のセットを定義するには、[a-z-[m]] を使用します。 "d"、"j" および "p" の文字を除外した基本グループで構成される文字のセットを定義するには、[a-z-[djp]] を使用します。 "m" ~ "p" の文字範囲を除外した基本グループで構成される文字のセットを定義するには、[a-z-[m-p]] を使用します。 入れ子になった文字クラス減算式 [a-z-[d-w-[m-o]]] について考えてみます。 この式は、最も内部の文字範囲から順に外側へと評価されます。 まず、"m" ~ "o" の文字範囲が "d" ~ "w" の文字範囲から減算されて、"d" ~ "l" および "p" ~ "w" の文字セットが生成されます。 さらにこのセットが "a" ~ "z" の文字範囲から減算されて、[abcmnoxyz] という文字セットが生成されます。 文字クラス減算では、任意の文字クラスを使用できます。 \u0000 ~ \uFFFF の Unicode 文字から空白文字 (\s)、句読点一般カテゴリの文字 (\p{P})、IsGreek 名前付きブロック内の文字 (\p{IsGreek})、および Unicode NEXT LINE 制御文字 (\x85) を除いた文字のセットを定義するには、[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]] を使用します。 有効な結果を生成する文字クラス減算式の文字クラスを選択します。 どの文字にも一致しない空の文字セットを生成する式、または元の基本グループと同じになる式は避けてください。 たとえば、[\p{IsBasicLatin}-[\x00-\x7F]] という式は、IsBasicLatin 一般カテゴリから IsBasicLatin 文字範囲のすべての文字を減算して空のセットを生成します。 同様に、[a-z-[0-9]] という式は元の基本グループと同じセットを生成します。 これは、"a" ~ "z" の文字範囲である基本グループに、"0" ~ "9" という 10 進数字の文字範囲から成る除外対象グループ内の文字が含まれないためです。 入力文字列内の 0 および奇数と一致する正規表現 ^[0-9-[2468]]+$ を定義する例を次に示します。 この正規表現の解釈を次の表に示します。 要素 | 説明 |
|---|
^ | 入力文字列の先頭から照合を開始します。 | [0-9-[2468]]+ | 2、4、6、および 8 を除く 0 ~ 9 の文字の 1 回以上の出現と一致します。 つまり、0 または奇数の 1 回以上の出現と一致します。 | $ | 入力文字列の末尾で照合を終了します。 |
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim inputs() As String = { "123", "13579753", "3557798", "335599901" }
Dim pattern As String = "^[0-9-[2468]]+$"
For Each input As String In inputs
Dim match As Match = Regex.Match(input, pattern)
If match.Success Then Console.WriteLine(match.Value)
Next
End Sub
End Module
' The example displays the following output:
' 13579753
' 335599901
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string[] inputs = { "123", "13579753", "3557798", "335599901" };
string pattern = @"^[0-9-[2468]]+$";
foreach (string input in inputs)
{
Match match = Regex.Match(input, pattern);
if (match.Success)
Console.WriteLine(match.Value);
}
}
}
// The example displays the following output:
// 13579753
// 335599901
ページのトップへ

参照
|