달력

1

« 2025/1 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2017. 5. 8. 16:55

.NET Framework Regular Expressions 프로그래밍/C#2017. 5. 8. 16:55


  1. .NET Framework Regular Expressions
  2. Regular Expression Language - Quick Reference



https://msdn.microsoft.com/en-us/library/hs600312(v=vs.110).aspx


.NET Framework Regular Expressions


Regular expressions provide a powerful, flexible, and efficient method for processing text. The extensive pattern-matching notation of regular expressions enables you to quickly parse large amounts of text to find specific character patterns; to validate text to ensure that it matches a predefined pattern (such as an e-mail address); to extract, edit, replace, or delete text substrings; and to add the extracted strings to a collection in order to generate a report. For many applications that deal with strings or that parse large blocks of text, regular expressions are an indispensable tool.

The centerpiece of text processing with regular expressions is the regular expression engine, which is represented by the System.Text.RegularExpressions.Regex object in the .NET Framework. At a minimum, processing text using regular expressions requires that the regular expression engine be provided with the following two items of information:

  • The regular expression pattern to identify in the text.

    In the .NET Framework, regular expression patterns are defined by a special syntax or language, which is compatible with Perl 5 regular expressions and adds some additional features such as right-to-left matching. For more information, see Regular Expression Language - Quick Reference.

  • The text to parse for the regular expression pattern.

The methods of the Regex class let you perform the following operations:

For an overview of the regular expression object model, see The Regular Expression Object Model.

For more information about the regular expression language, see Regular Expression Language - Quick Reference or download and print one of these brochures:

Quick Reference in Word (.docx) format
Quick Reference in PDF (.pdf) format

The String class includes a number of string search and replacement methods that you can use when you want to locate literal strings in a larger string. Regular expressions are most useful either when you want to locate one of several substrings in a larger string, or when you want to identify patterns in a string, as the following examples illustrate.

Example 1: Replacing Substrings

Assume that a mailing list contains names that sometimes include a title (Mr., Mrs., Miss, or Ms.) along with a first and last name. If you do not want to include the titles when you generate envelope labels from the list, you can use a regular expression to remove the titles, as the following example illustrates.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = "(Mr\\.? |Mrs\\.? |Miss |Ms\\.? )";
      string[] names = { "Mr. Henry Hunt", "Ms. Sara Samuels", 
                         "Abraham Adams", "Ms. Nicole Norris" };
      foreach (string name in names)
         Console.WriteLine(Regex.Replace(name, pattern, String.Empty));
   }
}
// The example displays the following output:
//    Henry Hunt
//    Sara Samuels
//    Abraham Adams
//    Nicole Norris

The regular expression pattern(Mr\.? |Mrs\.? |Miss |Ms\.? ) matches any occurrence of "Mr ", "Mr. ", "Mrs ", "Mrs. ", "Miss ", "Ms or "Ms. ". The call to the Regex.Replace method replaces the matched string with String.Empty; in other words, it removes it from the original string.

Example 2: Identifying Duplicated Words

Accidentally duplicating words is a common error that writers make. A regular expression can be used to identify duplicated words, as the following example shows.

using System;
using System.Text.RegularExpressions;

public class Class1
{
   public static void Main()
   {
      string pattern = @"\b(\w+?)\s\1\b";
      string input = "This this is a nice day. What about this? This tastes good. I saw a a dog.";
      foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase))
         Console.WriteLine("{0} (duplicates '{1}') at position {2}", 
                           match.Value, match.Groups[1].Value, match.Index);
   }
}
// The example displays the following output:
//       This this (duplicates 'This)' at position 0
//       a a (duplicates 'a)' at position 66

The regular expression pattern \b(\w+?)\s\1\b can be interpreted as follows:

\bStart at a word boundary.
(\w+?)Match one or more word characters, but as few characters as possible. Together, they form a group that can be referred to as \1.
\sMatch a white-space character.
\1Match the substring that is equal to the group named \1.
\bMatch a word boundary.

The Regex.Matches method is called with regular expression options set to RegexOptions.IgnoreCase. Therefore, the match operation is case-insensitive, and the example identifies the substring "This this" as a duplication.

Note that the input string includes the substring "this? This". However, because of the intervening punctuation mark, it is not identified as a duplication.

Example 3: Dynamically Building a Culture-Sensitive Regular Expression

The following example illustrates the power of regular expressions combined with the flexibility offered by the .NET Framework's globalization features. It uses the NumberFormatInfo object to determine the format of currency values in the system's current culture. It then uses that information to dynamically construct a regular expression that extracts currency values from the text. For each match, it extracts the subgroup that contains the numeric string only, converts it to a Decimal value, and calculates a running total.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Define text to be parsed.
      string input = "Office expenses on 2/13/2008:\n" + 
                     "Paper (500 sheets)                      $3.95\n" + 
                     "Pencils (box of 10)                     $1.00\n" + 
                     "Pens (box of 10)                        $4.49\n" + 
                     "Erasers                                 $2.19\n" + 
                     "Ink jet printer                        $69.95\n\n" + 
                     "Total Expenses                        $ 81.58\n"; 
      
      // Get current culture's NumberFormatInfo object.
      NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;
      // Assign needed property values to variables.
      string currencySymbol = nfi.CurrencySymbol;
      bool symbolPrecedesIfPositive = nfi.CurrencyPositivePattern % 2 == 0;
      string groupSeparator = nfi.CurrencyGroupSeparator;
      string decimalSeparator = nfi.CurrencyDecimalSeparator;

      // Form regular expression pattern.
      string pattern = Regex.Escape( symbolPrecedesIfPositive ? currencySymbol : "") + 
                       @"\s*[-+]?" + "([0-9]{0,3}(" + groupSeparator + "[0-9]{3})*(" + 
                       Regex.Escape(decimalSeparator) + "[0-9]+)?)" + 
                       (! symbolPrecedesIfPositive ? currencySymbol : ""); 
      Console.WriteLine( "The regular expression pattern is:");
      Console.WriteLine("   " + pattern);      

      // Get text that matches regular expression pattern.
      MatchCollection matches = Regex.Matches(input, pattern, 
                                              RegexOptions.IgnorePatternWhitespace);               
      Console.WriteLine("Found {0} matches.", matches.Count); 

      // Get numeric string, convert it to a value, and add it to List object.
      List<decimal> expenses = new List<Decimal>();
                     
      foreach (Match match in matches)
         expenses.Add(Decimal.Parse(match.Groups[1].Value));      

      // Determine whether total is present and if present, whether it is correct.
      decimal total = 0;
      foreach (decimal value in expenses)
         total += value;
      
      if (total / 2 == expenses[expenses.Count - 1]) 
         Console.WriteLine("The expenses total {0:C2}.", expenses[expenses.Count - 1]);
      else
         Console.WriteLine("The expenses total {0:C2}.", total);
   }  
}
// The example displays the following output:
//       The regular expression pattern is:
//          \$\s*[-+]?([0-9]{0,3}(,[0-9]{3})*(\.[0-9]+)?)
//       Found 6 matches.
//       The expenses total $81.58.

On a computer whose current culture is English - United States (en-US), the example dynamically builds the regular expression \$\s*[-+]?([0-9]{0,3}(,[0-9]{3})*(\.[0-9]+)?). This regular expression pattern can be interpreted as follows:

\$Look for a single occurrence of the dollar symbol ($) in the input string. The regular expression pattern string includes a backslash to indicate that the dollar symbol is to be interpreted literally rather than as a regular expression anchor. (The $ symbol alone would indicate that the regular expression engine should try to begin its match at the end of a string.) To ensure that the current culture's currency symbol is not misinterpreted as a regular expression symbol, the example calls the Escape method to escape the character.
\s*Look for zero or more occurrences of a white-space character.
[-+]?Look for zero or one occurrence of either a positive sign or a negative sign.
([0-9]{0,3}(,[0-9]{3})*(\.[0-9]+)?)The outer parentheses around this expression define it as a capturing group or a subexpression. If a match is found, information about this part of the matching string can be retrieved from the second Group object in the GroupCollection object returned by the Match.Groups property. (The first element in the collection represents the entire match.)
[0-9]{0,3}Look for zero to three occurrences of the decimal digits 0 through 9.
(,[0-9]{3})*Look for zero or more occurrences of a group separator followed by three decimal digits.
\.Look for a single occurrence of the decimal separator.
[0-9]+Look for one or more decimal digits.
(\.[0-9]+)?Look for zero or one occurrence of the decimal separator followed by at least one decimal digit.

If each of these subpatterns is found in the input string, the match succeeds, and a Match object that contains information about the match is added to the MatchCollection object.

TitleDescription
Regular Expression Language - Quick ReferenceProvides information on the set of characters, operators, and constructs that you can use to define regular expressions.
The Regular Expression Object ModelProvides information and code examples that illustrate how to use the regular expression classes.
Details of Regular Expression BehaviorProvides information about the capabilities and behavior of .NET Framework regular expressions.
Regular Expression ExamplesProvides code examples that illustrate typical uses of regular expressions.





Regular Expression Language - Quick Reference


A regular expression is a pattern that the regular expression engine attempts to match in input text. A pattern consists of one or more character literals, operators, or constructs. For a brief introduction, see .NET Framework Regular Expressions.

Each section in this quick reference lists a particular category of characters, operators, and constructs that you can use to define regular expressions:

Character escapes
Character classes
Anchors
Grouping constructs
Quantifiers
Backreference constructs
Alternation constructs
Substitutions
Regular expression options
Miscellaneous constructs

We’ve also provided this information in two formats that you can download and print for easy reference:

Download in Word (.docx) format
Download in PDF (.pdf) format

The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes.

Escaped characterDescriptionPatternMatches
\aMatches a bell character, \u0007.\a"\u0007" in "Error!" + '\u0007'
\bIn a character class, matches a backspace, \u0008.[\b]{3,}"\b\b\b\b" in "\b\b\b\b"
\tMatches a tab, \u0009.(\w+)\t"item1\t", "item2\t" in "item1\titem2\t"
\rMatches a carriage return, \u000D. (\r is not equivalent to the newline character, \n.)\r\n(\w+)"\r\nThese" in "\r\nThese are\ntwo lines."
\vMatches a vertical tab, \u000B.[\v]{2,}"\v\v\v" in "\v\v\v"
\fMatches a form feed, \u000C.[\f]{2,}"\f\f\f" in "\f\f\f"
\nMatches a new line, \u000A.\r\n(\w+)"\r\nThese" in "\r\nThese are\ntwo lines."
\eMatches an escape, \u001B.\e"\x001B" in "\x001B"
\ nnnUses octal representation to specify a character (nnn consists of two or three digits).\w\040\w"a b", "c d" in

"a bc d"
\x nnUses hexadecimal representation to specify a character (nn consists of exactly two digits).\w\x20\w"a b", "c d" in

"a bc d"
\c X

 \c x
Matches the ASCII control character that is specified by X or x, where X or x is the letter of the control character.\cC"\x0003" in "\x0003" (Ctrl-C)
\u nnnnMatches a Unicode character by using hexadecimal representation (exactly four digits, as represented by nnnn).\w\u0020\w"a b", "c d" in

"a bc d"
\When followed by a character that is not recognized as an escaped character in this and other tables in this topic, matches that character. For example, \* is the same as \x2A, and \. is the same as \x2E. This allows the regular expression engine to disambiguate language elements (such as * or ?) and character literals (represented by \* or \?).\d+[\+-x\*]\d+"2+2" and "3*9" in "(2+2) * 3*9"

Back to top

A character class matches any one of a set of characters. Character classes include the language elements listed in the following table. For more information, see Character Classes.

Character classDescriptionPatternMatches
[ character_group ]Matches any single character in character_group. By default, the match is case-sensitive.[ae]"a" in "gray"

"a", "e" in "lane"
[^ character_group ]Negation: Matches any single character that is not in character_group. By default, characters in character_group are case-sensitive.[^aei]"r", "g", "n" in "reign"
[ first - last ]Character range: Matches any single character in the range from first to last.[A-Z]"A", "B" in "AB123"
.Wildcard: Matches any single character except \n.

To match a literal period character (. or \u002E), you must precede it with the escape character (\.).
a.e"ave" in "nave"

"ate" in "water"
\p{ name }Matches any single character in the Unicode general category or named block specified by name.\p{Lu}

 \p{IsCyrillic}
"C", "L" in "City Lights"

"Д", "Ж" in "ДЖem"
\P{ name }Matches any single character that is not in the Unicode general category or named block specified by name.\P{Lu}

 \P{IsCyrillic}
"i", "t", "y" in "City"

"e", "m" in "ДЖem"
\wMatches any word character.\w"I", "D", "A", "1", "3" in "ID A1.3"
\WMatches any non-word character.\W" ", "." in "ID A1.3"
\sMatches any white-space character.\w\s"D " in "ID A1.3"
\SMatches any non-white-space character.\s\S" _" in "int __ctr"
\dMatches any decimal digit.\d"4" in "4 = IV"
\DMatches any character other than a decimal digit.\D" ", "=", " ", "I", "V" in "4 = IV"

Back to top

Anchors, or atomic zero-width assertions, cause a match to succeed or fail depending on the current position in the string, but they do not cause the engine to advance through the string or consume characters. The metacharacters listed in the following table are anchors. For more information, see Anchors.

AssertionDescriptionPatternMatches
^The match must start at the beginning of the string or line.^\d{3}"901" in

"901-333-"
$The match must occur at the end of the string or before \n at the end of the line or string.-\d{3}$"-333" in

"-901-333"
\AThe match must occur at the start of the string.\A\d{3}"901" in

"901-333-"
\ZThe match must occur at the end of the string or before \n at the end of the string.-\d{3}\Z"-333" in

"-901-333"
\zThe match must occur at the end of the string.-\d{3}\z"-333" in

"-901-333"
\GThe match must occur at the point where the previous match ended.\G\(\d\)"(1)", "(3)", "(5)" in "(1)(3)(5)[7](9)"
\bThe match must occur on a boundary between a \w (alphanumeric) and a \W(nonalphanumeric) character.\b\w+\s\w+\b"them theme", "them them" in "them theme them them"
\BThe match must not occur on a \b boundary.\Bend\w*\b"ends", "ender" in "end sends endure lender"

Back to top

Grouping constructs delineate subexpressions of a regular expression and typically capture substrings of an input string. Grouping constructs include the language elements listed in the following table. For more information, see Grouping Constructs.

Grouping constructDescriptionPatternMatches
( subexpression )Captures the matched subexpression and assigns it a one-based ordinal number.(\w)\1"ee" in "deep"
(?< name > subexpression )Captures the matched subexpression into a named group.(?<double>\w)\k<double>"ee" in "deep"
(?< name1 - name2 > subexpression )Defines a balancing group definition. For more information, see the "Balancing Group Definition" section in Grouping Constructs.(((?'Open'\()[^\(\)]*)+((?'Close-Open'\))[^\(\)]*)+)*(?(Open)(?!))$"((1-3)*(3-1))" in "3+2^((1-3)*(3-1))"
(?: subexpression )Defines a noncapturing group.Write(?:Line)?"WriteLine" in "Console.WriteLine()"

"Write" in "Console.Write(value)"
(?imnsx-imnsx: subexpression )Applies or disables the specified options within subexpression. For more information, see Regular Expression Options.A\d{2}(?i:\w+)\b"A12xl", "A12XL" in "A12xl A12XL a12xl"
(?= subexpression )Zero-width positive lookahead assertion.\w+(?=\.)"is", "ran", and "out" in "He is. The dog ran. The sun is out."
(?! subexpression )Zero-width negative lookahead assertion.\b(?!un)\w+\b"sure", "used" in "unsure sure unity used"
(?<= subexpression )Zero-width positive lookbehind assertion.(?<=19)\d{2}\b"99", "50", "05" in "1851 1999 1950 1905 2003"
(?<! subexpression )Zero-width negative lookbehind assertion.(?<!19)\d{2}\b"51", "03" in "1851 1999 1950 1905 2003"
(?> subexpression )Nonbacktracking (or "greedy") subexpression.[13579](?>A+B+)"1ABB", "3ABB", and "5AB" in "1ABB 3ABBC 5AB 5AC"

Back to top

A quantifier specifies how many instances of the previous element (which can be a character, a group, or a character class) must be present in the input string for a match to occur. Quantifiers include the language elements listed in the following table. For more information, see Quantifiers.

QuantifierDescriptionPatternMatches
*Matches the previous element zero or more times.\d*\.\d".0", "19.9", "219.9"
+Matches the previous element one or more times."be+""bee" in "been", "be" in "bent"
?Matches the previous element zero or one time."rai?n""ran", "rain"
{ n }Matches the previous element exactly n times.",\d{3}"",043" in "1,043.6", ",876", ",543", and ",210" in "9,876,543,210"
{ n ,}Matches the previous element at least n times."\d{2,}""166", "29", "1930"
{ n , m }Matches the previous element at least n times, but no more than m times."\d{3,5}""166", "17668"

"19302" in "193024"
*?Matches the previous element zero or more times, but as few times as possible.\d*?\.\d".0", "19.9", "219.9"
+?Matches the previous element one or more times, but as few times as possible."be+?""be" in "been", "be" in "bent"
??Matches the previous element zero or one time, but as few times as possible."rai??n""ran", "rain"
{ n }?Matches the preceding element exactly n times.",\d{3}?"",043" in "1,043.6", ",876", ",543", and ",210" in "9,876,543,210"
{ n ,}?Matches the previous element at least n times, but as few times as possible."\d{2,}?""166", "29", "1930"
{ n , m }?Matches the previous element between n and m times, but as few times as possible."\d{3,5}?""166", "17668"

"193", "024" in "193024"

Back to top

A backreference allows a previously matched subexpression to be identified subsequently in the same regular expression. The following table lists the backreference constructs supported by regular expressions in the .NET Framework. For more information, see Backreference Constructs.

Backreference constructDescriptionPatternMatches
\ numberBackreference. Matches the value of a numbered subexpression.(\w)\1"ee" in "seek"
\k< name >Named backreference. Matches the value of a named expression.(?<char>\w)\k<char>"ee" in "seek"

Back to top

Alternation constructs modify a regular expression to enable either/or matching. These constructs include the language elements listed in the following table. For more information, see Alternation Constructs.

Alternation constructDescriptionPatternMatches
&#124;Matches any one element separated by the vertical bar (|) character.th(e&#124;is&#124;at)"the", "this" in "this is the day. "
(?( expression ) yes &#124; no )Matches yes if the regular expression pattern designated by expression matches; otherwise, matches the optional no part. expression is interpreted as a zero-width assertion.(?(A)A\d{2}\b&#124;\b\d{3}\b)"A10", "910" in "A10 C103 910"
(?( name ) yes &#124; no )Matches yes if name, a named or numbered capturing group, has a match; otherwise, matches the optional no.(?<quoted>")?(?(quoted).+?"&#124;\S+\s)Dogs.jpg, "Yiska playing.jpg" in "Dogs.jpg "Yiska playing.jpg""

Back to top

Substitutions are regular expression language elements that are supported in replacement patterns. For more information, see Substitutions. The metacharacters listed in the following table are atomic zero-width assertions.

CharacterDescriptionPatternReplacement patternInput stringResult string
$ numberSubstitutes the substring matched by group number.\b(\w+)(\s)(\w+)\b$3$2$1"one two""two one"
${ name }Substitutes the substring matched by the named group name.\b(?<word1>\w+)(\s)(?<word2>\w+)\b${word2} ${word1}"one two""two one"
$$Substitutes a literal "$".\b(\d+)\s?USD$$$1"103 USD""$103"
$&Substitutes a copy of the whole match.\$?\d*\.?\d+**$&**"$1.30""**$1.30**"
`$``Substitutes all the text of the input string before the match.B+`$``"AABBCC""AAAACC"
$'Substitutes all the text of the input string after the match.B+$'"AABBCC""AACCCC"
$+Substitutes the last group that was captured.B+(C+)$+"AABBCCDD"AACCDD
$_Substitutes the entire input string.B+$_"AABBCC""AAAABBCCCC"

Back to top

You can specify options that control how the regular expression engine interprets a regular expression pattern. Many of these options can be specified either inline (in the regular expression pattern) or as one or more RegexOptions constants. This quick reference lists only inline options. For more information about inline and RegexOptions options, see the article Regular Expression Options.

You can specify an inline option in two ways:

  • By using the miscellaneous construct(?imnsx-imnsx), where a minus sign (-) before an option or set of options turns those options off. For example, (?i-mn) turns case-insensitive matching (i) on, turns multiline mode (m) off, and turns unnamed group captures (n) off. The option applies to the regular expression pattern from the point at which the option is defined, and is effective either to the end of the pattern or to the point where another construct reverses the option.

  • By using the grouping construct(?imnsx-imnsx:subexpression), which defines options for the specified group only.

The .NET Framework regular expression engine supports the following inline options.

OptionDescriptionPatternMatches
iUse case-insensitive matching.\b(?i)a(?-i)a\w+\b"aardvark", "aaaAuto" in "aardvark AAAuto aaaAuto Adam breakfast"
mUse multiline mode. ^ and $ match the beginning and end of a line, instead of the beginning and end of a string.For an example, see the "Multiline Mode" section in Regular Expression Options.
nDo not capture unnamed groups.For an example, see the "Explicit Captures Only" section in Regular Expression Options.
sUse single-line mode.For an example, see the "Single-line Mode" section in Regular Expression Options.
xIgnore unescaped white space in the regular expression pattern.\b(?x) \d+ \s \w+"1 aardvark", "2 cats" in "1 aardvark 2 cats IV centurions"

Back to top

Miscellaneous constructs either modify a regular expression pattern or provide information about it. The following table lists the miscellaneous constructs supported by the .NET Framework. For more information, see Miscellaneous Constructs.

ConstructDefinitionExample
(?imnsx-imnsx)Sets or disables options such as case insensitivity in the middle of a pattern.For more information, see Regular Expression Options.\bA(?i)b\w+\b matches "ABA", "Able" in "ABA Able Act"
(?# comment )Inline comment. The comment ends at the first closing parenthesis.\bA(?#Matches words starting with A)\w+\b
# [to end of line]X-mode comment. The comment starts at an unescaped # and continues to the end of the line.(?x)\bA\w+\b#Matches words starting with A









'프로그래밍 > C#' 카테고리의 다른 글

Tuple Class  (0) 2017.05.08
Memory Management and Garbage Collection in the .NET Framework  (0) 2017.05.08
Data Parallelism (Task Parallel Library)  (0) 2017.05.06
Task  (0) 2017.04.22
Task-based Asynchronous Programming  (0) 2017.04.22
:
Posted by 지훈2