Using regular expressions in Java programming _java

Source: Internet
Author: User

In the process of programming, often need to check the data format entered, then will use the regular expression, matching the regular expression of the data format is correct, otherwise malformed. In order to check whether the data entered satisfies a certain format, you can use the matches () method of the string class to determine the syntax format as follows:

Boolean matches (String regex)

Regex: The specified regular expression.
Return value: Returns a Boolean type.
This method is used to tell if the current string matches the regular expression specified by the parameter regex, the return value is a Boolean, and if the current string matches the regular expression, the method returns True, or false.

A regular expression is a string of characters that contain special meanings. These characters, which contain special meaning, are called metacharacters, the partial metacharacters of regular expressions are listed below, and in the writing of regular expressions, the "\" notation is added before the following metacharacters, such as the meta character "\d" In the regular expression is "\d", but for ".", the translation does not represent any one character, but represents a specific period.

.: Represents any one character.
\d: Represents any number of 0~9.
\d: Represents any number of non-numeric characters.
\s: Represents a blank character.
\s: Represents a non-white-space character.
\w: Represents a character that can be used as an identifier, but does not include "$".
\w: Represents a character that cannot be used as an identifier.
\p{lower}: Represents the lowercase letter a~z.
\p{upper}: Represents the capital letter A~a.
\p{ascii}:ascii characters.
\p{alpha}: Alphabetic characters.
\p{digit}: Decimal digits, 0~9.
\p{alnum}: Numeric or alphabetic characters.
\P{PUNCT}: Punctuation.
\p{graph}: Visible characters.
\p{print}: Printable character.
\p{blank}: Blank or tab.
\p{cntrl}: Control character.

When using regular expressions, if you need a type of metacharacters to output multiple times, typing is rather cumbersome, you can use the qualifier character of the regular expression to repeat the number of times, and the common qualifiers and their meanings are listed below.

?: 0 times or 1 times.
*: 0 or more times.
+:0 or 1 times.
{n}: repeat n times.
{N,}: Repeat at least n times.
{n,m}: Repeat N~m time.

In a regular expression, you can also enclose multiple characters in square brackets, with various regular expressions in brackets representing different meanings, and the metacharacters and their meanings in square brackets are listed below.

[ABC]: Represents a, B, or C.
[^ABC]: represents any character other than a, B, and C.
[Any character of a-za-z]:a~z or a~z.
[Any character of a-d[m-p]]:a~d or m~p.
[A-z&&[def]]:d, E or F.
[A-z&&[^bc]]:a~z does not contain all characters between B and C.
[All characters with m~p are not included between a-z&&[^m-p]]:a~z.


Usage Examples:
1. License Number:

/**

* * 

@description: Verify license plate number

* @param carnum *      a106ek

* @return valid: True illegal: false

*/ public static Boolean Validatecarnum (String carnum) {

Boolean result = false;

String[] Provence = new string[] {"Jing", "Jin", "Ji", "Jin", "Liao", "Ji", "Black", "Shanghai", "su", "Zhe", "Wan", "Min", "Gan", "Lu", "Yu", "E", "Xiang", "Yue "," GUI "," Joan "," Yu ",

" Chuan "," Qian "," Dian "," Tibet "," Shaanxi "," Gan "," Qing "," Ning "," New "," Hong Kong "," O "," Meng "};

String reg = "[\u4e00-\u9fa5]{1}[a-z]{1}[a-z_0-9]{5}";

Boolean firstchar = false;

if (carnum.length () > 0) {

Firstchar = Arrays.aslist (Provence). Contains (carnum.substring (0, 1));

try {pattern

p = pattern.compile (reg);

Matcher m = P.matcher (carnum);

if (m.matches () && firstchar) {result

= true;

} else {result

= false;

}

catch (Except Ion e) {

e.printstacktrace ();

}

return result;

}

2, mobile phone number:

/**

* * 

@description: Verify mobile phone number

* @param mobilenum 15516985859

* @return valid: True not valid: false

*/ public static Boolean Ismobilenum (String mobilenum) {

Boolean result = false;

try {pattern

p = pattern.compile ("^ (13[0-9]) |" ( 15[^4,\\D]) | (18[0,5-9]) \\d{8}$ ");

Matcher m = P.matcher (mobilenum);

result = M.matches ();

} catch (Exception e) {

e.printstacktrace ();

}

return result;

}


Mobile number + Fixed Telephone: 010-1111111,15516985859,0377-1111111

Java detection is a phone number (cell phone, fixed telephone authentication)

String legalphone = "";
String RegExp = "^ (13[0-9]) | ( 15[^4,\\D]) | (18[0,5-9]) \\d{8}| [0] {1} [0-9] {2,3}-[0-9]{7,8}$ ";
Pattern p = pattern.compile (REGEXP);
Matcher m = P.matcher (Importpotentialbfos[i].getlegalphone ());
if (M.find ()) {//Note: M.find can only be used once, the second call is false
 Legalphone = Importpotentialbfos[i].getlegalphone ();
 Uploadtmp.setlegaltelephone (Legalphone);

} else{
 throw new Bizexception ("Contact phone format error!");
}

3. Real number:

String[] Arrs=new string[]{"A", "1.123", " -1.23", "0", "+111"};

      String regex= "-?\\d+\\." \\d* ";

      Pattern p = pattern.compile (regex);

      for (int i = 0; i < arrs.length i++) {

       Matcher m = P.matcher (arrs[i));

       System.out.println (arrs[i]+ ":" +m.matches ());

 }

Print:

A:false

1.123:true

-1.23:true

0:true

+111:false

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.