C # regular expression,

Source: Internet
Author: User
Tags control characters

C # regular expression,

This is obtained from the Internet. You can add backups to your favorites, which can save a lot of time!

Only numbers are allowed: "^ [0-9] * $ ".

Only n digits can be entered: "^ \ d {n} $ ".

You can only enter at least n digits: "^ \ d {n,} $ ".

Only m ~ can be input ~ N-digit: "^ \ d {m, n} $ ".

Only numbers starting with zero and non-zero can be entered: "^ (0 | [1-9] [0-9] *) $ ".

Only positive numbers with two decimal places can be entered: "^ [0-9] + (. [0-9] {2 })? $ ".

Only 1 ~ Positive number of three decimal places: "^ [0-9] + (. [0-9] {1, 3 })? $ ".

Only a non-zero positive integer can be entered: "^ \ +? [1-9] [0-9] * $ ".

Only a non-zero negative integer can be entered: "^ \-[1-9] [] 0-9" * $.

Only 3 characters can be entered: "^. {3} $ ".

You can only enter A string consisting of 26 English letters: "^ [A-Za-z] + $ ".

You can only enter a string consisting of 26 uppercase letters: "^ [A-Z] + $ ".

You can only enter a string consisting of 26 lower-case English letters: "^ [a-z] + $ ".

You can only enter a string consisting of a number and 26 English letters: "^ [A-Za-z0-9] + $ ".

You can only enter a string consisting of digits, 26 English letters, or underscores (_): "^ \ w + $ ".

Verify the User Password: "^ [a-zA-Z] \ w {5, 17} $". The correct format is: start with a letter, with a length of 6 ~ It can only contain characters, numbers, and underscores.

Check whether ^ % & ',; =? $ \ "And other characters:" [^ % & ',; =? $ \ X22] + ".

Only Chinese characters can be entered: "^ [\ u4e00-\ u9fa5] {0,} $"

Verify Email address: "^ \ w + ([-+.] \ w +) * @ \ w + ([-.] \ w + )*\. \ w + ([-.] \ w +) * $ ".

Verify InternetURL: "^ http: // ([\ w-] + \.) + [\ w-] + (/[\ w -./? % & =] *)? $ ".

Image extraction address:/(http (s )? \:\/\/)? (Www \.)? (\ W + \: \ d + )? (\/\ W +) + \. (png | gif | jpg | bmp | jpeg)/gi.

Verification phone number: "^ (\ d {3, 4}-) | \ d {3.4 }-)? \ D {7,8} $ "correct format:" XXX-XXXXXXX "," XXXX-XXXXXXXX "," XXX-XXXXXXX "," XXX-XXXXXXXX "," XXXXXXX "and" XXXXXXXX ".

Verify the ID card number (15 or 18 digits): "^ \ d {15} | \ d {18} $ ".

12 months of verification: "^ (0? [1-9] | 1 [0-2]) $ "the correct format is:" 01 "~ "09" and "1 "~ "12 ".

31 days of verification for a month: "^ (0? [1-9]) | (1 | 2) [0-9]) | 30 | 31) $ "the correct format is;" 01 "~ "09" and "1 "~ "31 ".


Javascript programs that extract file names from URLs using regular expressions. the following result is page1.

The following is a reference clip:
S = "http://www.9499.net/page1.htm"
S = s. replace (/(. * \/) {0,} ([^ \.] +). */ig, "$2 ")
Alert (s)

 

Match double-byte characters (including Chinese characters): [^ \ x00-\ xff]

Application: Calculate the length of a string (two-byte length Meter 2, ASCII character meter 1)

The following is a reference clip:
String. prototype. len = function () {return this. replace ([^ \ x00-\ xff]/g, "aa"). length ;}

 

Regular Expression for matching empty rows: \ n [\ s |] * \ r

Regular Expressions matching HTML tags:/<(. *)>. * <\/\ 1> | <(. *) \/>/

Regular Expression matching spaces at the beginning and end: (^ \ s *) | (\ s * $)

The following is a reference clip:
String. prototype. trim = function ()
{
Return this. replace (/(^ \ s *) | (\ s * $)/g ,"");
}

 

  Use regular expressions to break down and convert IP addresses:

The following is a Javascript program that uses regular expressions to match IP addresses and convert IP addresses to corresponding values:

The following is a reference clip:
Function IP2V (ip)
{
Re =/(\ d +) \. (\ d +)/g // Regular Expression matching IP addresses
If (re. test (ip ))
{
Return RegExp. $1 * Math. pow (255) + RegExp. $2 * Math. pow () + RegExp. $3 * + RegExp. $4*1
}
Else
{
Throw new Error ("Not a valid IP address! ")
}
}


Symbol explanation:
\
Mark the next character as a special character, a literal character, or a backward reference, or an octal escape character. For example, 'n' matches the character "n ". '\ N' matches a line break. The sequence '\' matches "\" and "\ (" matches "(".
^
Matches the start position of the input string. If the Multiline attribute of the RegExp object is set, ^ matches the position after '\ n' or' \ R.
$
Matches the end position of the input string. If the Multiline attribute of the RegExp object is set, $ also matches the position before '\ n' or' \ R.
*
Matches the previous subexpression zero or multiple times. For example, zo * can match "z" and "zoo ". * Is equivalent to {0 ,}.
+
Match the previous subexpression once or multiple times. For example, 'Zo + 'can match "zo" and "zoo", but cannot match "z ". + Is equivalent to {1 ,}.
?
Match the previous subexpression zero or once. For example, "do (es )? "Can match" do "in" do "or" does ".? It is equivalent to {0, 1 }.
{N}
N is a non-negative integer. Match n times. For example, 'O {2} 'cannot match 'O' in "Bob", but can match two o in "food.
{N ,}
N is a non-negative integer. Match at least n times. For example, 'O {2,} 'cannot match 'O' in "Bob", but can match all o in "foooood. 'O {1,} 'is equivalent to 'o + '. 'O {0,} 'is equivalent to 'o *'.
{N, m}
Both m and n are non-negative integers, where n <= m. Match at least n times and at most m times. For example, "o {1, 3}" matches the first three o in "fooooood. 'O {0, 1} 'is equivalent to 'o? '. Note that there must be no space between a comma and two numbers.
?
When this character is followed by any other delimiter (*, + ,?, The matching mode after {n}, {n ,}, {n, m}) is not greedy. The non-Greedy mode matches as few searched strings as possible, while the default greedy mode matches as many searched strings as possible. For example, for strings "oooo", 'O ++? 'Will match a single "o", and 'O +' will match all 'O '.
.
Matches any single character except "\ n. To match any character including '\ n', use a pattern like' [. \ n.
(Pattern)
Match pattern and obtain this match. The obtained match can be obtained from the generated Matches set. The SubMatches set is used in VBScript, and $0… is used in JScript... $9 attribute. To match the parentheses, use ''or ′'.
(? : Pattern)
Matches pattern but does not get the matching result. That is to say, this is a non-get match and is not stored for future use. This is useful when you use the "or" character (|) to combine each part of a pattern. For example, 'industr (? : Y | ies) is a simpler expression than 'industry | industries.
(? = Pattern)
Forward pre-query: matches the search string at the beginning of any string that matches the pattern. This is a non-get match, that is, the match does not need to be obtained for future use. For example, 'windows (? = 95 | 98 | NT | 2000) 'can match "Windows" in "Windows 2000", but cannot match "Windows" in "Windows 3.1 ". Pre-query does not consume characters, that is, after a match occurs, the next matching search starts immediately after the last match, instead of starting after the pre-query characters.
(?! Pattern)
Negative pre-query: matches the search string at the beginning of any string that does not match pattern. This is a non-get match, that is, the match does not need to be obtained for future use. For example, 'windows (?! 95 | 98 | NT | 2000) 'can match "Windows" in "Windows 3.1", but cannot match "Windows" in "Windows 2000 ". Pre-query does not consume characters. That is to say, after a match occurs, the next matching search starts immediately after the last match, instead of starting after the pre-query characters.
X | y
Match x or y. For example, 'z | food' can match "z" or "food ". '(Z | f) ood' matches "zood" or "food ".
[Xyz]
Character Set combination. Match any character in it. For example, '[abc]' can match 'A' in "plain '.
[^ Xyz]
Negative value character set combination. Match any character not included. For example, '[^ abc]' can match 'p' in "plain '.
[A-z]
Character range. Matches any character in the specified range. For example, '[a-z]' can match any lowercase letter in the range of 'A' to 'Z.
[^ A-z]
Negative character range. Matches any character that is not within the specified range. For example, '[^ a-z]' can match any character that is not in the range of 'A' to 'Z.
\ B
Match A Word boundary, that is, the position between a word and a space. For example, 'er \ B 'can match 'er' in "never", but cannot match 'er 'in "verb '.
\ B
Match non-word boundary. 'Er \ B 'can match 'er' in "verb", but cannot match 'er 'in "never '.
\ Cx
Match the control characters specified by x. For example, \ cM matches a Control-M or carriage return character. The value of x must be either a A-Z or a-z. Otherwise, c is treated as an original 'C' character.
\ D
Match a numeric character. It is equivalent to [0-9].
\ D
Match a non-numeric character. It is equivalent to [^ 0-9].
\ F
Match a form feed. It is equivalent to \ x0c and \ cL.
\ N
Match A linefeed. It is equivalent to \ x0a and \ cJ.
\ R
Match a carriage return. It is equivalent to \ x0d and \ cM.
\ S
Matches any blank characters, including spaces, tabs, and page breaks. It is equivalent to [\ f \ n \ r \ t \ v].
\ S
Match any non-blank characters. It is equivalent to [^ \ f \ n \ r \ t \ v].
\ T
Match a tab. It is equivalent to \ x09 and \ cI.
\ V
Match a vertical tab. It is equivalent to \ x0b and \ cK.
\ W
Match any word characters that contain underscores. It is equivalent to '[A-Za-z0-9 _]'.
\ W
Match any non-word characters. It is equivalent to '[^ A-Za-z0-9 _]'.
\ Xn
Match n, where n is the hexadecimal escape value. The hexadecimal escape value must be determined by the length of two numbers. For example, '\ x41' matches "". '\ X041' is equivalent to '\ x04' & "1 ". The regular expression can use ASCII encoding ..
\ Num
Matches num, where num is a positive integer. References to the obtained matching. For example, '(.) \ 1' matches two consecutive identical characters.
\ N
Identifies an octal escape value or a backward reference. If at least n subexpressions are obtained before \ n, n is backward referenced. Otherwise, if n is an octal digit (0-7), n is an octal escape value.
\ Nm
Identifies an octal escape value or a backward reference. If at least one child expression is obtained before \ nm, the nm is backward referenced. If at least n records are obtained before \ nm, n is a backward reference followed by text m. If none of the preceding conditions are met, if n and m are Octal numbers (0-7), \ nm matches the octal escape value nm.
\ Nml
If n is an octal number (0-3) and m and l are Octal numbers (0-7), the octal escape value nml is matched.
\ Un
Match n, where n is a Unicode character represented by four hexadecimal numbers. For example, \ u00A9 matches the copyright symbol (?).


Application:

C # Regular Expression # region Regular Expression string // <summary> // Regular Expression string // </summary> public class StrRegex {# region Regular Expression replacement string/ // <summary> /// Replace the string with a regular expression /// </summary> /// <param name = "inputString"> string content </param> /// <param name = "pattern"> replacement character </param> /// <param name = "replaceStr"> replacement value </param> /// <returns> </returns> public static string RegexReplace (string inputString, string pattern, string replaceStr) {try {Return Regex. replace (inputString, pattern, replaceStr);} catch (Exception e) {return e. message ;}} # endregion # region determine whether the string is a positive integer // <summary> // determine whether the string is a positive integer /// </summary> /// <param name = "objString"> The string to be matched </param> // <returns> returns the true value, true: match; false: Mismatch </returns> public static bool IsInt (String objString) {Regex myReg = new Regex (@ "^ \ d + $"); return myReg. isMatch (objString) ;}# endregion # regi On determines whether all input strings are English (Case Insensitive) /// <summary> // determines whether all input strings are English (Case Insensitive) /// </summary> /// <param name = "objString"> the string to be matched </param> /// <returns> returns the true value, true: match; false: Mismatch </returns> public static bool isEnglishString (String objString) {Regex myReg = new Regex (@ "^ [a-zA-Z] + $ "); return myReg. isMatch (objString );} # endregion // <summary> // return the number in the string /// </summary> /// <param name = "objString"> </param> /// <Returns> </returns> public static string RunNumber (string objString) {return Regex. match (objString, "[0-9] + "). value. toString ();} /// <summary> /// returns the character on the left of the string /// </summary> /// <param name = "objString"> </param> /// <returns> </returns> public static string RunLeftString (string objString) {return Regex. match (objString, "[% */+ -. a-Za-z] + "). value. toString () ;}//< summary> /// return the character on the right of the string /// </su Mmary> /// <param name = "objString"> </param> /// <returns> </returns> public static string RunRightString (string objString) {return Regex. match (objString, "[% */+ -. a-Za-z] + $ "). value. toString ();} /// <summary> /// return the characters in the string /// </summary> /// <param name = "objString"> </param> // <returns> </returns> public static string RunString (string objString) {return Regex. match (objString, "[A-Za-z] + "). value. T OString ();} # region judge whether the input string is Chinese // <summary> /// determine whether the input string is Chinese // </summary> /// <param name = "objString"> the string to be matched </param> // <returns> returns the true value, true: match; false: Mismatch </returns> public static bool isChinese (String objString) {Regex myReg = new Regex (@ "^ [\ u4e00-\ u9fa5] + $"); return myReg. isMatch (objString) ;}# endregion # region determines whether the input string is an English or a number (English is case insensitive) /// <summary> /// determines whether the input string is an English or a number (English is case insensitive )/// </Summary> /// <param name = "objString"> the string to be matched </param> /// <returns> returns the true value. true: match; false: mismatch </returns> public static bool isEngNum (String objString) {Regex myReg = new Regex (@ "^ [*/+-a-zA-Z0-9] + $"); return myReg. isMatch (objString) ;}# endregion # region determines whether the input string is an English A-D and number (English restrictions are case-insensitive between A-D) /// <summary> /// determines whether the input string is an English A-D and number (English only between A-D) /// </summary> /// <param name = "objString"> the character to be matched String </param> // <returns> returns the true value, true: matching; false: not matching </returns> public static bool isEngNumMax (String objString) {Regex myReg = new Regex (@ "^ [a-dA-D0-9] + $"); return myReg. isMatch (objString );} # endregion # Check whether region is a combination of English letters and numbers /// <summary> /// check whether it is a combination of English letters and numbers /// </summary> /// <param name = "objString"> </param> // <returns> </returns> public static bool InEngNum (string objString) {// Regex myReg = new Regex (@ "^ (?! [0-9] + $) [a-zA-Z0-9] {25} $ "); // return myReg. isMatch (objString); "^ [a-zA-Z] \ w {5, 17} $" return Regex. isMatch (objString, @ "^ [*/+-a-zA-Z0-9] {} $");} # endregion # region judge whether the input string is English, number, chinese (English is case insensitive) /// <summary> /// determines whether the input string is English, numbers, and Chinese (English is case insensitive) /// </summary> /// <param name = "objString"> the string to be matched </param> /// <returns> returns the true value, true: match; false: Mismatch </returns> public static bool isChineseEngNum (String objString) {Regex myReg = new Regex (@ "^ [\ u4e00-\ u9fa5a-zA-Z0-9] + $"); return myReg. isMatch (objString );} # endregion # region determines whether the input string is a decimal number. /// <summary> /// determines whether the input string is a decimal number. /// </summary> /// <param name =" objString "> the string to be matched </param> // <returns> returns the true value, true: match; false: Mismatch </returns> public static bool isFloat (String objString) {Regex myReg = new Regex (@ "^ [0-9] + [.] [0-9] + | [0-9] + $ "); return myReg. isMatch (objString );} # Endregion # region determine whether the date format is valid // <summary> // determine whether the date format is valid // </summary> /// <param name = "objString "> </param> /// <returns> </returns> public static bool IsDate (String objString) {Regex myReg = new Regex (@ "\ B (? <Year> \ d {2, 4 })-(? <Month> \ d {1, 2 })-(? <Day> \ d {1, 2}) \ B "); return myReg. isMatch (objString );} # endregion # region test whether the string matches the regular expression // <summary> // test whether the string matches the regular expression // </summary> // <param name = "str"> string to be matched </param> // <param name = "regString"> regular string (for example: ^ [1-9] {1 }$) </param> // <returns> returns the true value. true: match; false: mismatch </returns> public static bool IsFitStrings (String str, String regString) {Regex objPattern = new Regex (regString); bool returnValue = ObjPattern. isMatch (str); return returnValue ;} # endregion # region determine whether the string is a mobile phone number or PHS number // <summary> // determine whether the string is a mobile phone number or PHS number /// </summary> /// <param name = "telNumber"> the string to be matched </param> // <returns> returns the true value, true: match; false: Mismatch </returns> public static bool IsMobile (string telNumber) {if (telNumber = "") return false; regex myReg = new Regex (@ "^ (\ d {11,12}) | (\ d {7}) $"); return myReg. isMatch (telNumber );}# Endregion # region determine whether the string is an Email address // <summary> /// determine whether the string is an Email address /// </summary> /// <param name = "email "> the string to be matched </param> // <returns> returns the true value, true: match; false: Mismatch </returns> public static bool IsEmail (string email) {if (email = "") {return false ;} regex myReg = new Regex (@ "^ \ w + ([-+.] \ w +) * @ \ w + ([-.] \ w + )*\. \ w + ([-.] \ w +) * $ "); return myReg. isMatch (email) ;}# endregion # region determines whether the string is a landline (for example, xxx-xxxxxxx-xx) X) /// <summary> /// determines whether the string is a landline (for example, xxx-xxxxxxx-xxx) /// </summary> /// <param name = "tel"> string to be matched </param> /// <returns> returns the true value, true: match; false: Mismatch </returns> public static bool IsTel (string tel) {if (tel = "") return false; regex myReg = new Regex (@ "^ (\ d {3, 4} \) | \ d {3, 4 }-)? \ D {7, 8} (-\ d {1, 5 })? $ "); Return myReg. isMatch (tel );} # endregion # region determine whether it is a Zip code // <summary> /// determine whether it is a Zip code /// </summary> /// <param name = "Zip"> </param> // <returns> </returns> public static bool IsValidZip (string Zip) {return Regex. isMatch (Zip, @ "^ [a-z0-9] {} $ ");} # endregion # Check whether region is a valid ID card number /// <summary> /// check whether it is a valid ID card number /// </summary> /// <param name = "IdCard"> </param> /// <returns> </returns> public static bool IsIdCard (string IdCard) {return Regex. isMatch (IdCard, @ "^ \ d {15} | \ d {18} $ ");} # endregion # region returns the split string /// <summary> /// returns the split string /// </summary> /// <param name = "Str"> string set </param> /// <param name = "spliststr"> specify delimiter </param> /// <returns> </returns> public static string FindStr (string str, string spliststr) {string [] str2 = System. text. regularExpressions. regex. split (Str, @ "[" + spliststr + "] +"); foreach (string I in str2) {return I. toString () ;}return "" ;}# endregion }# endregion



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.