C# regular expressions based on Unity, and a summary of some commonly used matching methods

1. Briefly introduce
some basic knowledge points in Unity to facilitate later viewing and learning.

This section introduces the application knowledge of regular expressions in Unity, and summarizes some commonly used matching methods.

1. Some commonly used regular expression matching methods
1. ^\d+$ //Match non-negative integers (positive integers + 0)

2. ^[0-9]*[1-9][0-9]*$ //Match positive integers

3. ^((-\d+)|(0+))$ //Match non-positive integers (negative integers + 0)

4. ^-[0-9]*[1-9][0-9]*$ //Match negative integers

5. ^-?\d+$ //Match integers

6. ^\d+(\.\d+)?$ //Match non-negative floating point numbers (positive floating point numbers + 0)

7. ^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\. [0-9]+)|([0-9]*[1-9][0-9]*))$ //Match positive floating point numbers

8. ^((-\d+(\.\d+)?)|(0+(\.0+)?))$ //Match non-positive floating point numbers (negative floating point numbers + 0)

9. ^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]* \.[0-9]+)|([0-9]*[1-9][0-9]*)))$ //Match negative floating point numbers

10. ^(-?\d+)(\.\d+)?$ //Match floating point numbers

11. ^[A-Za-z]+$ //Match a string consisting of 26 English letters

12. ^[AZ]+$ //Match a string consisting of 26 uppercase English letters

13. ^[az]+$ //Match a string consisting of 26 lowercase English letters

14. ^[A-Za-z0-9]+$ //Match a string consisting of numbers and 26 English letters

15. ^\w+$ //Match a string consisting of numbers, 26 English letters or underscores

16. ^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$ //Match email address

17. ^[a-zA-z]+://The size (\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$ //The size url

18. Regular expression to match Chinese characters: [\u4e00-\u9fa5]

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

20. Application: Calculate the length of a string (a double-byte character counts as 2, and an ASCII character counts as 1)

String.prototype.len=function(){return this.replace([^\x00-\xff]/g,"aa").length;}

twenty one. Regular expression to match empty lines: \n[\s| ]*\r

twenty two. Regular expression matching HTML tags: /<(.*)>.*<\/\1>|<(.*) \/>/

twenty three. Regular expression matching leading and trailing spaces: (^\s*)|(\s*$)

2. Regular expression use case
1. ^\S+[az AZ]$ cannot be empty, cannot have spaces, and can only be English letters.

2. \S{6,} cannot be empty for more than six digits

3. ^\d+$ cannot have spaces or non-digits

4. (.*)(\.jpg|\.bmp)$ can only be in jpg and bmp formats

5. ^\d{4}\-\d{1,2}-\d{1,2}$ can only be in 2004-10-22 format

6. ^0$ Select at least one item

7. ^0{2,}$ Choose at least two items

8. ^[\s|\S]{20,}$ cannot be empty for more than 20 characters.

9、^\+?[a-z0-9](([-+.]|[_]+)?[a-z0-9]+)*@([a-z0-9]+(\. |\-))+[az]{2,6}$邮件

10.\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;]\s*\w+( [-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)* Enter multiple addresses and separate emails with commas or spaces.

11. ^([0−9]+
[
0

9
]
+
)?[0-9]{7,8}$ The phone number is 7 or 8 digits or preceded by an area code, for example (022) 87341628

12、^[a-z A-Z 0-9 _]+@[a-z A-Z 0-9 _]+(\.[a-z A-Z 0-9 _]+)+(\,[a-z A-Z 0-9 _]+@[a-z A-Z 0-9 _]+(\.[a-z A-Z 0-9 _]+)+)*$

It can only be letters, numbers, and underscores; it must contain @ and. At the same time, the format must be standardized.

13 ^\w+@\w+(\.\w+)+(\,\w+@\w+(\.\w+)+)*$ The above expression can also be written like this, which is more concise.

14 ^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$

This is just a simple summary to make it easier for you to use in the future.

Regular expression to match Chinese characters: [\u4e00-\u9fa5]

Comment: Matching Chinese is really a headache. With this expression, it will be easier.

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

Comment: Can be used to calculate the length of a string (a double-byte character counts as 2, and an ASCII character counts as 1)

Regular expression to match blank lines: \n\s*\r

Comment: Can be used to delete blank lines

Regular expression to match HTML tags: <(\S*?)[^>]*>.*? | <.*? />

Comment: The version circulating on the Internet is too bad. The above one can only match part of it, and it is still powerless for complex nested tags.

Regular expression matching leading and trailing whitespace characters: ^\s* |\s*$

Comment: It can be used to delete whitespace characters (including spaces, tabs, form feeds, etc.) at the beginning and end of the line. It is a very useful expression.

Regular expression matching email addresses: \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

Comment: Very useful for form validation

Regular expression to match URL: [a-zA-z]+://[^\s]*

Comment: The version circulating on the Internet has very limited functions. The above one can basically meet the needs.

Is the matching account legal (starting with a letter, 5-16 bytes allowed, alphanumeric underscores allowed): ^[a-zA-Z][a-zA-Z0-9_]{4,15}$

Comment: Very useful for form validation

Match domestic phone numbers:\d{3}-\d{8} |\d{4}-\d{7}

Comment: Matching format such as 0511-4405222 or 021-87888822

Match Tencent QQ number: [1-9][0-9]{4,}

Comment: Tencent QQ account starts from 10000

Match Chinese postal code: [1-9]\d{5}(?!\d)

Comment: China’s postal code is a 6-digit number

Matching ID card:\d{15} |\d{18}

Comment: China’s ID card has 15 or 18 digits

Match ip address:\d+\.\d+\.\d+\.\d+

Comment: Useful when extracting IP address

3. Match specific numbers:
^[1-9]\d*$ //Match positive integers

^-[1-9]\d*$ //Match negative integers

^-?[1-9]\d*$ //Match integers

^[1-9]\d* ?0$ //Match non-negative integers (positive integers + 0)

^-[1-9]\d* ?0$ //Match non-positive integers (negative integers + 0)

^[1-9]\d*\.\d* ?0\.\d*[1-9]\d*$ //Match positive floating point numbers

^-([1-9]\d*\.\d* ?0\.\d*[1-9]\d*)$ //Match negative floating point numbers

^-?([1-9]\d*\.\d* ?0\.\d*[1-9]\d* ?0?\.0+ ?0)$ //Match floating point numbers

^[1-9]\d*\.\d* ?0\.\d*[1-9]\d* ?0?\.0+ ?0$ //Match non-negative floating point numbers (positive floating point numbers + 0)

^(-([1-9]\d*\.\d* ?0\.\d*[1-9]\d*)) ?0?\.0+ ?0$ //Match non-positive float Points (negative float + 0)

Comment: Useful when processing large amounts of data, please pay attention to corrections when applying it.

4. Match a specific string:
^[A-Za-z]+$ //Match a string consisting of 26 English letters

^[AZ]+$ //Match a string consisting of 26 uppercase English letters

^[az]+$ //Match a string consisting of 26 lowercase English letters

^[A-Za-z0-9]+$ //Match a string consisting of numbers and 26 English letters

^\w+$ //Match a string consisting of numbers, 26 English letters or underscores

"^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+___FCKpd___0quot; //email address

"^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?___FCKpd___0quot;  //url

Regular expression to match Chinese characters: [\u4e00-\u9fa5]

Comment: Matching Chinese is really a headache. With this expression, it will be easier.

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

Comment: Can be used to calculate the length of a string (a double-byte character counts as 2, and an ASCII character counts as 1)

Regular expression to match blank lines: \n\s*\r

Comment: Can be used to delete blank lines

Regular expression to match HTML tags: <(\S*?)[^>]*>.*? | <.*? />

Comment: The version circulating on the Internet is too bad. The above one can only match part of it, and it is still powerless for complex nested tags.

Regular expression matching leading and trailing whitespace characters: ^\s* |\s*$

Comment: It can be used to delete whitespace characters (including spaces, tabs, form feeds, etc.) at the beginning and end of the line. It is a very useful expression.

Regular expression matching email addresses: \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

Comment: Very useful for form validation

Regular expression to match URL: [a-zA-z]+://[^\s]*

Comment: The version circulating on the Internet has very limited functions. The above one can basically meet the needs.

Is the matching account legal (starting with a letter, 5-16 bytes allowed, alphanumeric underscores allowed): ^[a-zA-Z][a-zA-Z0-9_]{4,15}$

Comment: Very useful for form validation

Match domestic phone numbers:\d{3}-\d{8} |\d{4}-\d{7}

Comment: Matching format such as 0511-4405222 or 021-87888822

Match Tencent QQ number: [1-9][0-9]{4,}

Comment: Tencent QQ account starts from 10000

Match Chinese postal code: [1-9]\d{5}(?!\d)

Comment: China’s postal code is a 6-digit number

Matching ID card:\d{15} |\d{18}

Comment: China’s ID card has 15 or 18 digits

Match ip address:\d+\.\d+\.\d+\.\d+

Comment: Useful when extracting IP address

5. Several basic concepts of regularity:
1. Greedy: +,*,?,{m,n}, etc. are greedy matching by default, that is, matching as many as possible, also called maximum matching

If ? is added after it, it will be converted into non-greedy matching, which requires higher version support.

2. Acquisition: The default use of (x ?y) is to obtain matching. In many cases, it is just for testing and does not necessarily require obtaining the matched data. Especially in nested matching or big data, non-acquisition matching (?:x ?y is required) ), which improves efficiency and optimizes the program.

3. Consumption: The default is consumption matching, generally it is non-consumption matching in pre-checking.

For example, 2003-2-8 should be changed to 2003-02-08

If you use /-(\d)(?=-)/, the second match starts from the second -, that is, no characters are consumed.

4. Pre-check: js is divided into positive pre-check and negative pre-check

For example, the above (?=pattern) is a forward lookup, matching the search string at the beginning of any string matching pattern. Also (?!pattern) is a negative lookup, which matches the search string at the beginning of any string that does not match pattern. Negative lookahead is sometimes used to expand [^]. [^] is just some characters, while ?! can make the entire string. view plaincopy to clipboardprint?

5. Callback: Generally used for substitution, that is, returning different replacement values ​​based on different matching contents, thus simplifying the program and requiring higher version support.

6. Reference: \num refers to the reference to the obtained numth match.

For example, '(.)\1\1' matches type AAA. '(.)(.)\2\1' matches ABBA type.

6. Regular expression reserved words
^ (carat)

. (period)

[ (left bracket}

$ (dollar sign)

( (left parenthesis)

) (right parenthesis)

| (pipe)

* (asterisk)

+ (plus symbol)

? (question mark)

{ (left curly bracket, or left brace)

\ backslash view plaincopy to clipboardprint?

constructed to match

7. Character
x Character x

\\ backslash character

\0n octal value of character 0n (0 <= n <= 7)

\0nn octal value of character 0nn (0 <= n <= 7)

\0mnn Octal value character 0mnn 0mnn (0 <= m <= 3, 0 <= n <= 7)

\xhh Hexadecimal value of character 0xhh

\uhhhh Hexadecimal value of character 0xhhhh

\ttab('\u0009')

\n newline character ('\u000A')

\r carriage return ('\u000D')

\f form feed ('\u000C')

\a bell symbol('\u0007')

\e escape character ('\u001B')

\cx T corresponds to the control character x of x

 8. Character class
[abc] a, b, or c (simple class)

[^abc] Any character except a, b or c (negation)

[a-zA-Z] a to z or A to Z, inclusive (range)

[az-[bc]] a to z, except b and c: [ad-z] (subtract)

[az-[mp]] a to z, except m to p: [a-lq-z]

[a-z-[^def]] d, e, 或 f view plaincopy to clipboardprint?

9. Predefined character classes:
any character (maybe able to match line terminators, maybe not)

\d Number: [0-9]

\D non-digit: [^0-9]

\s space character: [ \t\n\x0B\f\r]

\S non-space character: [^\s]

\w word character: [a-zA-Z_0-9]

\W non-word characters: [^\w]

I found this from the Internet, save it for later use, it will save a lot of time when you use it!

Only numbers can be entered: "^[0-9]*$" .

Only n-digit numbers can be entered: "^\d{n}$".

Only numbers with at least n digits can be entered: "^\d{n,}$".

Only m~n numbers can be entered: "^\d{m,n}$".

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

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

Only positive real numbers with 1 to 3 decimal places can be entered: "^[0-9]+(.[0-9]{1,3})?$".

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

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

Only characters with a length of 3 can be entered: "^.{3}$".

Only a string consisting of 26 English letters can be entered: "^[A-Za-z]+$".

Only a string consisting of 26 uppercase English letters can be entered: "^[AZ]+$".

Only a string consisting of 26 lowercase English letters can be entered: "^[az]+$".

Only a string consisting of numbers and 26 English letters can be entered: "^[A-Za-z0-9]+$".

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

Verify user password: "^[a-zA-Z]\w{5,17}$" The correct format is: starts with a letter, has a length between 6 and 18, and can only contain characters, numbers and underscores.

Verify whether it contains characters such as ^%&',;=?$\": "[^%&',;=?$\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-./?%&=]*)?$".

     Extract image 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}$" The correct format is: "XXX-XXXXXXX", "XXXX-XXXXXXXX ", "XXX-XXXXXXX", "XXX-XXXXXXXX", "XXXXXXX" and "XXXXXXXX".

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

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

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


A javascript program that uses regular expressions to extract file names from URL addresses. The following result is page1
 

The following is a quotation fragment:
  s="http://www.9499.net/page1.htm"
  s=s.replace(/(.*\/){0,}([^\.]+).*/ ig,"$2")
  alert(s)
matches double-byte characters (including Chinese characters): [^\x00-\xff]

  Application: Calculate the length of a string (a double-byte character counts as 2, and an ASCII character counts as 1)

The following is a quote fragment:
  String.prototype.len=function(){return this.replace([^\x00-\xff]/g,"aa").length;}
Regular expression matching empty lines:\n[ \s| ]*\r

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

  Regular expression matching leading and trailing spaces: (^\s*)|(\s*$)

The following is a reference fragment:
  String.prototype.trim = function()
  {   return this.replace(/(^\s*)|(\s*$)/g, "");   } Use regular expressions to decompose and convert IP address:


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

The following is a reference fragment:
function IP2V(ip)
{ re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //Regular expression matching IP address if( re .test(ip)) { return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1 } else { throw new Error("Not a valid IP address!") } } Symbol explanation: \ marks the next character as a special character, or a literal character, or a backward reference, or an octal escape character. For example, 'n' matches the character "n". '\ n' matches a newline character. The sequence '\\' matches "\" and "\(" matches "(". ^ matches the beginning of the input string. If the Multiline property of the RegExp object is set, ^ also matches '\ n' or '\r'. $ matches the end of the input string. If the Multiline property of the RegExp object is set, $ also matches the position before '\n' or '\r'. * matches the preceding sub Zero or more occurrences of an expression. For example, zo* matches "z" and "zoo". * is equivalent to {0,}. +




















Matches the preceding subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
?
Match the preceding subexpression zero or one time. For example, "do(es)?" matches "do" or "do" in "does". ? Equivalent to {0,1}.
{n}
n is a nonnegative integer. Match determined n times. For example, 'o{2}' cannot match the 'o' in "Bob", but it can match the two o's in "food".
{n,}
n is a nonnegative integer. Match at least n times. For example, 'o{2,}' does not match the 'o' in "Bob", but it matches all o's in "foooood". 'o{1,}' is equivalent to 'o+'. 'o{0,}' is equivalent to 'o*'.
{n,m}
m and n are both non-negative integers, where n <= m. Match at least n times and at most m times. For example, "o{1,3}" will match the first three o's in "fooooood". 'o{0,1}' is equivalent to 'o?'. Please note that there cannot be a space between the comma and the two numbers.
?
When this character is immediately followed by any other qualifier (*, +, ?, {n}, {n,}, {n, m}), the matching pattern is non-greedy. Non-greedy mode matches as little of the searched string as possible, while the default greedy mode matches as much of the searched string as possible. For example, for the string "oooo", 'o+?' will match a single "o", while 'o+' will match all 'o's.
.matches
any single character except "\n". To match any character including '\n', use a pattern like '[.\n]'.
(pattern)
Match pattern and get this match. The matches obtained can be obtained from the generated Matches collection, using the SubMatches collection in VBScript or the $0…$9 properties in JScript. To match parentheses characters, use ' ' or ' '.
(?:pattern)
matches pattern but does not obtain the matching result, which means that this is a non-acquisition match and is not stored for later use. This is useful when using the "or" character (|) to combine parts of a pattern. For example, 'industr(?:y|ies) is a shorter expression than 'industry|industries'.
(?=pattern)
forward lookup, matching the search string at the beginning of any string matching pattern. This is a non-fetch match, that is, the match does not need to be fetched for later use. For example, 'Windows (?=95|98|NT|2000)' matches "Windows" in "Windows 2000" but not "Windows" in "Windows 3.1". Prefetching does not consume characters, that is, after a match occurs, the search for the next match begins immediately after the last match, rather than starting after the character containing the prefetch.
(?!pattern)
Negative lookup, matches the search string at the beginning of any string that does not match pattern. This is a non-fetch match, that is, the match does not need to be fetched for later use. For example 'Windows (?!95|98|NT|2000)' would match "Windows 3.

Match x or y. For example, 'z|food' matches "z" or "food". '(z|f)ood' matches "zood" or "food".
[xyz]
character set. Matches any one of the characters contained. For example, '[abc]' matches 'a' in "plain".
[^xyz]
Negative value character set. Matches any character not included. For example, '[^abc]' matches the 'p' in "plain".
[az]
Character range. Matches any character within the specified range. For example, '[az]' matches any lowercase alphabetic character in the range 'a' through 'z'.
[^az]
Negative character range. Matches any character not within the specified range. For example, '[^az]' matches any character that is not in the range 'a' to 'z'.
\b
matches a word boundary, which is the position between a word and a space. For example, 'er\b' matches the 'er' in "never" but not the 'er' in "verb".
\B
matches non-word boundaries. 'er\B' matches the 'er' in "verb", but not the 'er' in "never".
   \cx
matches the control character specified by x. For example, \cM matches a Control-M or carriage return character. The value of x must be one of AZ or az. Otherwise, c is treated as a literal 'c' character.
\d
matches a numeric character. Equivalent to [0-9].
\D
matches a non-numeric character. Equivalent to [^0-9].
\f
matches a form feed character. Equivalent to \x0c and \cL.
\n
matches a newline character. Equivalent to \x0a and \cJ.
\r
matches a carriage return character. Equivalent to \x0d and \cM.
\s
matches any whitespace character, including spaces, tabs, form feeds, etc. Equivalent to [ \f\n\r\t\v].
\S
matches any non-whitespace character. Equivalent to [^ \f\n\r\t\v].
\t
matches a tab character. Equivalent to \x09 and \cI.
\v
matches a vertical tab character. Equivalent to \x0b and \cK.
\w
matches any word character including an underscore. Equivalent to '[A-Za-z0-9_]'.
\W
matches any non-word character. Equivalent to '[^A-Za-z0-9_]'.
\xn
matches n, where n is the hexadecimal escape value. The hexadecimal escape value must be exactly two digits long. For example, '\x41' matches "A". '\x041' is equivalent to '\x04' & "1". ASCII encoding can be used in regular expressions. .
\num
matches num, where num is a positive integer. A reference to the match obtained. For example, '(.)\1' matches two consecutive identical characters.
\nIdentifies
an octal escape value or a backreference. If \n is preceded by at least n fetched subexpressions, n is a backward reference. Otherwise, if n is an octal number (0-7), then n is an octal escape value.
\nm
identifies an octal escape value or a backreference. If \nm is preceded by at least nm get-subexpressions, nm is a backward reference. If \nm is preceded by at least n acquisitions, n is a backward reference followed by the literal m. If none of the previous conditions are met, then \nm will match the octal escape value nm if n and m are both octal numbers (0-7).
\nmlIf
n is an octal digit (0-3), and m and l are both octal digits (0-7), then matches the octal escape value nml.
\un
matches n, where n is a Unicode character represented by four hexadecimal digits. For example, \u00A9 matches the copyright symbol (?).
 

10. Some code examples
C# regular expression collection

#region 正则表达式字符串
    /// <summary>
    /// 正则表达式字符串
    /// </summary>
    public class StrRegex
    {
        #region 正则表达式替换字符串
        /// <summary>
        /// 正则表达式替换字符串
        /// </summary>
        /// <param name="inputString">字符串内容</param>
        /// <param name="pattern">替换字符</param>
        /// <param name="replaceStr">替换值</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 判断字符串是否为正整数
        /// <summary>
        /// 判断字符串是否为正整数
        /// </summary>
        /// <param name="objString">要匹配的字符串</param>
        /// <returns>返回真假值,true:匹配;false:不匹配</returns>
        public static bool IsInt(String objString)
        {
            Regex myReg = new Regex(@"^\d+$");
            return myReg.IsMatch(objString);
        }
        #endregion
 
        #region 判断输入的字符串是否全是英文(不区分大小写)
        /// <summary>
        /// 判断输入的字符串是否全是英文(不区分大小写)
        /// </summary>
        /// <param name="objString">所要匹配的字符串</param>
        /// <returns>返回真假值,true:匹配;false:不匹配</returns>
        public static bool isEnglishString(String objString)
        {
            Regex myReg = new Regex(@"^[a-zA-Z]+$");
            return myReg.IsMatch(objString);
        }
        #endregion
 
        /// <summary>
        /// 返回字符串中的数字
        /// </summary>
        /// <param name="objString"></param>
        /// <returns></returns>
        public static string RunNumber(string objString)
        {
            return Regex.Match(objString, "[0-9]+").Value.ToString();
        }
 
        /// <summary>
        /// 返回字符串中左边的字符
        /// </summary>
        /// <param name="objString"></param>
        /// <returns></returns>
        public static string RunLeftString(string objString)
        {
            return Regex.Match(objString, "[%*/+ -.A-Za-z]+").Value.ToString();
        }
 
        /// <summary>
        /// 返回字符串中右边的字符
        /// </summary>
        /// <param name="objString"></param>
        /// <returns></returns>
        public static string RunRightString(string objString)
        {
            return Regex.Match(objString, "[%*/+ -.A-Za-z]+$").Value.ToString();
        }
 
        /// <summary>
        /// 返回字符串中的字符
        /// </summary>
        /// <param name="objString"></param>
        /// <returns></returns>
        public static string RunString(string objString)
        {
            return Regex.Match(objString, "[A-Za-z]+").Value.ToString();
        }
 
        #region 判断所输入的字符串是否为中文
        /// <summary>
        /// 判断所输入的字符串是否为中文
        /// </summary>
        /// <param name="objString">所要匹配的字符串</param>
        /// <returns>返回真假值,true:匹配;false:不匹配</returns>
        public static bool isChinese(String objString)
        {
            Regex myReg = new Regex(@"^[\u4e00-\u9fa5]+$");
            return myReg.IsMatch(objString);
        }
        #endregion
 
        #region 判断输入字符串是否为英文及数字(英文不区分大小写)
        /// <summary>
        /// 判断输入字符串是否为英文及数字(英文不区分大小写)
        /// </summary>
        /// <param name="objString">所要匹配的字符串</param>
        /// <returns>返回真假值,true:匹配;false:不匹配</returns>
        public static bool isEngNum(String objString)
        {
            Regex myReg = new Regex(@"^[*/+-a-zA-Z0-9]+$");
            return myReg.IsMatch(objString);
        }
        #endregion
 
        #region 判断输入字符串是否为英文A-D及数字(英文限制在A-D之间英文不区分大小写)
        /// <summary>
        /// 判断输入字符串是否为英文A-D及数字(英文限制在A-D之间英文不区分大小写)
        /// </summary>
        /// <param name="objString">所要匹配的字符串</param>
        /// <returns>返回真假值,true:匹配;false:不匹配</returns>
        public static bool isEngNumMax(String objString)
        {
            Regex myReg = new Regex(@"^[a-dA-D0-9]+$");
            return myReg.IsMatch(objString);
        }
        #endregion
 
        #region  判断是否为英文及数字组合
        /// <summary>
        /// 判断是否为英文及数字组合
        /// </summary>
        /// <param name="objString"></param>
        /// <returns></returns>
        public static bool InEngNum(string objString)
        {
            //Regex myReg = new Regex(@"^(?![0-9]+$)[a-zA-Z0-9]{1,25}$");           
            //return myReg.IsMatch(objString);"^[a-zA-Z]\w{5,17}$"
            return Regex.IsMatch(objString, @"^[*/+-a-zA-Z0-9]{1,20}$");
        }
        #endregion
 
        #region 判断输入字符串是否为英文,数字,中文(英文不区分大小写)
        /// <summary>
        /// 判断输入字符串是否为英文,数字,中文(英文不区分大小写)
        /// </summary>
        /// <param name="objString">所要匹配的字符串</param>
        /// <returns>返回真假值,true:匹配;false:不匹配</returns>
        public static bool isChineseEngNum(String objString)
        {
            Regex myReg = new Regex(@"^[\u4e00-\u9fa5a-zA-Z0-9]+$");
            return myReg.IsMatch(objString);
        }
        #endregion
 
        #region 判断输入字符串是否为小数
        /// <summary>
        /// 判断输入字符串是否为小数
        /// </summary>
        /// <param name="objString">所要匹配的字符串</param>
        /// <returns>返回真假值,true:匹配;false:不匹配</returns>
        public static bool isFloat(String objString)
        {
            Regex myReg = new Regex(@"^[0-9]+[.][0-9]+|[0-9]+$");
            return myReg.IsMatch(objString);
        }
        #endregion
 
        #region 判断日期格式是否有效
        /// <summary>
        /// 判断日期格式是否有效
        /// </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 判断字符串是否符合此正则表达试
        /// <summary>
        /// 判断字符串是否符合此正则表达试
        /// </summary>
        /// <param name="str">所要匹配的字符串</param>
        /// <param name="regString">正则字符串(如:^[1-9]{1}$)</param>
        /// <returns>返回真假值,true:匹配;false:不匹配</returns>
        public static bool IsFitStrings(String str, String regString)
        {
            Regex objPattern = new Regex(regString);
            bool returnValue = objPattern.IsMatch(str);
            return returnValue;
        }
        #endregion
 
        #region 判断字符串是否为手机号或小灵通号
        /// <summary>
        /// 判断字符串是否为手机号或小灵通号
        /// </summary>
        /// <param name="telNumber">所要匹配的字符串</param>
        /// <returns>返回真假值,true:匹配;false:不匹配</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 判断字符串是否为Email地址
        /// <summary>
        /// 判断字符串是否为Email地址
        /// </summary>
        /// <param name="email">所要匹配的字符串</param>
        /// <returns>返回真假值,true:匹配;false:不匹配</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 判断字符串是否为座机(如xxx-xxxxxxx-xxx)
        /// <summary>
        /// 判断字符串是否为座机(如xxx-xxxxxxx-xxx)
        /// </summary>
        /// <param name="tel">所要匹配的字符串</param>
        /// <returns>返回真假值,true:匹配;false:不匹配</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 判断是否为邮政编码
        /// <summary>
        /// 判断是否为邮政编码
        /// </summary>
        /// <param name="Zip"></param>
        /// <returns></returns>
        public static bool IsValidZip(string Zip)
        {
            return Regex.IsMatch(Zip, @"^[a-z0-9 ]{3,12}$");
        }
        #endregion
 
        #region  判断是否为有效身份证号
        /// <summary>
        /// 判断是否为有效身份证号
        /// </summary>
        /// <param name="IdCard"></param>
        /// <returns></returns>
        public static bool IsIdCard(string IdCard)
        {
            return Regex.IsMatch(IdCard, @"^\d{15}|\d{18}$");
        }
        #endregion
 
        #region 返回分割字符串
        /// <summary>
        /// 返回分割字符串
        /// </summary>
        /// <param name="Str">要分割的字符串集</param>
        /// <param name="spliststr">指定分割字符</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


 
——————————————
Copyright Statement: This article is an original article by CSDN blogger “Xiankui XAN” and follows the CC 4.0 BY-SA copyright agreement. For reprinting, please attach the original source link and this statement.
Original link: https://blog.csdn.net/u014361280/article/details/98514826

Guess you like

Origin blog.csdn.net/qq_37524903/article/details/132525022