Regular Expression in Android

Source: Internet
Author: User
Regular Expression to find characters

String s_result = "distance: 2.8 km (about 9 mins )";

// Distance Parsing
Pattern P = pattern. Compile ("distance: (\ D + (\. \ D + )?) (.*?) \ B ");
Matcher M = P. matcher (s_result );
If (M. Find ()){
Matchresult mr = M. tomatchresult ();
F_distance = mr. Group (1); // 2.8
M_distanceunit = mr. Group (3); // km
}

// Time Parsing
P = pattern. Compile ("about (\ D + (\. \ D + )?) (. *) \ B ");
M = P. matcher (s_result );
If (M. Find ()){
Matchresult mr = M. tomatchresult ();
F_timeest = mr. Group (1); // 9
M_timeestunit = mr. Group (3); // min
}
Or
String s_result = "distance: 2.8 km (about 9 mins )";
Pattern P = pattern. Compile ("(\ D + (\. \ D + )?) ? (\ W + ?) \ B ");
Matcher M = P. matcher (s_result );
While (M. Find ()){
Matchresult mr = M. tomatchresult ();
String value = mr. Group (1); // 2.8 and 9 come here
String Units = mr. Group (3); // km and mins come here
}

Regular Expression to filter out special characters

I haven't found a suitable regular expression on the Internet for a long time to filter out special characters. I learned it myself and wrote two expressions to meet the requirements.
Java code
// Filter special characters
Public static string stringfilter (string Str) throws patternsyntaxexception {

// Only letters and numbers are allowed
// String RegEx = "[^ a-zA-Z0-9]";
// Clear all special characters
String RegEx = "['~! @ # $ % ^ & * () + =|{} ':;', \ [\]. <> /?~! @ # ¥ % ...... & Amp; * () -- + | {} [] ';: "'., ,?] ";

Pattern P = pattern. Compile (RegEx );
Matcher M = P. matcher (STR );
Return M. replaceall (""). Trim ();
}
@ Test
Public void teststringfilter () throws patternsyntaxexception {

String STR = "* adcvs * 34_a _ 09_b5*[/435 ^ * & Chengchi () ^ $ &*). {} +. | .) % *(*. china} 34 {45 [] 12. FD '* & 999 is the Chinese character ¥ ...... {}【].,; '? ";

System. Out. println (STR );
System. Out. println (stringfilter (STR ));
}
// Filter special characters public static string stringfilter (string Str) throws patternsyntaxexception {// only letters and numbers are allowed // string RegEx = "[^ a-zA-Z0-9]"; // clear all special characters string RegEx = "['~! @ # $ % ^ & * () + =|{} ':;', \ [\]. <> /?~! @ # ¥ % ...... & * () -- + | {} [] ';: "'., ,?] "; Pattern P = pattern. Compile (RegEx );
Matcher M = P. matcher (STR); Return M. replaceall (""). trim () ;}@ test public void teststringfilter () throws patternsyntaxexception {string STR = "* adcvs * 34_a _ 09_b5*[/435 ^ * & Chengchi () ^ $ &*). {} +. | .) % *(*. china} 34 {45 [] 12. FD '* & 999 is the Chinese character ¥ ...... {}【].,; '? "; System. Out. println (STR );
System. Out. println (stringfilter (STR ));}

We use JUnit for testing. Of course you can change it to main.

Java Regular Expression learning:
Because regular expressions are a complex system, this example only introduces some concepts. For more information, see related books and explore for yourself.

\ Backslash
\ T interval ('\ u0009 ')
\ N line feed ('\ u000a ')
\ R press enter ('\ u000d ')
The \ D number is equivalent to [0-9].
\ D is equivalent to [^ 0-9].
\ S blank symbol [\ t \ n \ x0b \ f \ r]
\ S non-blank symbol [^ \ t \ n \ x0b \ f \ r]
\ W single character [a-zA-Z_0-9]
\ W non-single character [^ a-zA-Z_0-9]
\ F page feed
\ E escape
\ B boundary of a word
\ B a non-word boundary
End of the match before \ G

^ Starts with a limit.
^ Java conditions must start with Java
$ Is the end of the limit.
Java $ condition is limited to the end character of Java
. The condition limits any single character except \ n.
Java .. the condition is limited to any two characters except line breaks after Java

Add the specified condition "[]"
[A-Z] the condition is limited to one character in the lowercase A to Z range.
[A-Z] conditions are limited to one character in the upper case A to Z range
[A-Za-Z] the condition is limited to one character in the lowercase A to Z or uppercase A to Z range.
[0-9] the condition is limited to one character in the lowercase 0 to 9 Range
[0-9a-z] the condition is limited to one character in the lowercase 0 to 9 or A to Z range.
[0-9 [A-Z] the condition is limited to one character (intersection) in the lowercase 0 to 9 or A to Z range)

[] Add ^ and then add the restriction "[^]"
[^ A-Z] the condition is limited to one character in the range of non-lowercase A to Z
[^ A-Z] conditions are limited to one character in the range of not uppercase A to Z
[^ A-Za-Z] the condition is limited to one character in the range of non-lowercase A to Z or uppercase A to Z.
[^ 0-9] the condition is limited to one character in the range of 0 to 9 in non-lowercase letters.
[^ 0-9a-z] the condition is limited to one character in the range of 0 to 9 or A to Z in non-lowercase letters.
[^ 0-9 [A-Z] the condition is limited to one character (intersection) in the range of non-lowercase 0 to 9 or A to Z)

When the limit is 0 or more times for a specific character, you can use 「*」
J * more than 0 J
. * 0 or more arbitrary characters
J. * d j and D must contain more than 0 arbitrary characters.

When the condition is that a specific character appears more than once, you can use "+ 」
J + 1 or more J
. + 1 or more arbitrary characters
More than one arbitrary character between J. + d j and D

You can use "?" When the limit is 0 or more times for a specific character 「?」
Ja? J or ja appears

Limit to the number of consecutive occurrences of the specified character "{}」
J {2} jj
J {3} jjj
More than a characters, and "{,}」
J {3,} jjj, jjjj, jjjjj ,??? (More than three J events coexist)
More than one text, less than B "{a, B }」
J {3, 5} jjj, jjjj, or jjjjj
Take the two as "| 」
J | a j or
Java | Hello Java or hello

Specifies a combination type in "()".
For example, you can write <. * href = \". * \ "> (. + ?) </A>

When using the pattern. Compile function, you can add parameters that control the Matching Behavior of Regular Expressions:
Pattern pattern. Compile (string RegEx, int flag)

The flag value range is as follows:
Pattern. canon_eq is determined to be matched only when the "Canonical Decomposition" of the two characters are identical. For example, if this sign is used, the expression "a \ u030a" will match "? ". By default, canonical equivalence is not considered )".

Pattern. case_insensitive (? I) by default, Case Insensitive matching applies only to the US-ASCII character set. This flag allows the expression to ignore the case sensitivity for matching. To match the size of a Unicode character with an unknown size, you just need to combine the unicode_case and the flag.

Pattern. Comments (? X) In this mode, space characters (in a regular expression) are ignored during matching ", it refers to the space in the expression, tab, and press Enter ). The comment starts from # and ends with this line. You can enable the Unix line mode through the embedded flag.

Pattern. dotall (? S) In this mode, the expression '.' can match any character, including the end character of a row. By default, the expression '.' does not match the end character of the row.
Pattern. multiline
(? M) In this mode, '^' and '$' match the start and end of a row respectively. In addition, '^' still matches the start of the string, '$' also matches the end of the string. By default, these two expressions only match the start and end of the string.

Pattern. unicode_case
(? U) In this mode, If you enable the case_insensitive flag, it will match Unicode characters in case insensitive. By default, case-insensitive matching applies only to the US-ASCII character set.

Pattern. unix_lines (? D) In this mode, only '\ n' is considered as a row stop and matches'. ',' ^ ', and' $.

Aside from the vague concept, let's write a few simple Java regular use cases:

◆ For example, when the string contains Verification

// Search for any string starting with Java and ending
Pattern pattern = pattern. Compile ("^ java .*");
Matcher = pattern. matcher ("Java is not a person ");
Boolean B = matcher. Matches ();
// If the condition is met, true is returned; otherwise, false is returned.
System. Out. println (B );

◆ When a string is separated by multiple conditions
Pattern pattern = pattern. Compile ("[, |] + ");
String [] STRs = pattern. Split ("Java Hello World Java, hello, world | sun ");
For (INT I = 0; I <STRs. length; I ++ ){
System. Out. println (STRs [I]);
}

◆ Text replacement (first occurrence of characters)
Pattern pattern = pattern. Compile ("Regular Expression ");
Matcher = pattern. matcher ("Regular Expression Hello world, regular expression Hello World ");
// Replace the first regular data
System. Out. println (matcher. replacefirst ("Java "));

◆ Text replacement (all)
Pattern pattern = pattern. Compile ("Regular Expression ");
Matcher = pattern. matcher ("Regular Expression Hello world, regular expression Hello World ");
// Replace the first regular data
System. Out. println (matcher. replaceall ("Java "));

◆ Text replacement (replacement character)
Pattern pattern = pattern. Compile ("Regular Expression ");
Matcher = pattern. matcher ("Regular Expression Hello world, regular expression Hello World ");
Stringbuffer SBR = new stringbuffer ();
While (matcher. Find ()){
Matcher. appendreplacement (SBR, "Java ");
}
Matcher. appendtail (SBR );
System. Out. println (SBR. tostring ());

◆ Verify whether the email address is used

String STR = "ceponline@yahoo.com.cn ";
Pattern pattern = pattern. compile ("[\ W \\. \-] + @ ([\ W \-] + \\.) + [\ W \-] + ", pattern. case_insensitive );

Matcher = pattern. matcher (STR );
System. Out. println (matcher. Matches ());

◆ Remove HTML tags
Pattern pattern = pattern. Compile ("<. +?> ", Pattern. dotall );
Matcher = pattern. matcher ("<a href = \" index.html \ "> homepage </a> ");
String string = matcher. replaceall ("");
System. Out. println (string );

◆ Search for the corresponding condition string in HTML
Pattern pattern = pattern. Compile ("href = \" (. + ?) \"");
Matcher = pattern. matcher ("<a href = \" index.html \ "> homepage </a> ");
If (matcher. Find ())
System. Out. println (matcher. Group (1 ));
}

◆ Intercept http: // address
// Intercept the URL
Pattern pattern = pattern. Compile ("(http: // | https: //) {1} [\ W \. \-/:] + ");
Matcher = pattern. matcher ("dsdsds Stringbuffer buffer = new stringbuffer ();
While (matcher. Find ()){
Buffer. append (matcher. Group ());
Buffer. append ("\ r \ n ");
System. Out. println (buffer. tostring ());
}

◆ Replace the specified {} text

String STR = "Java's current development history is from {0}-{1} years ";
String [] [] object = {New String [] {"\\{ 0 \\}", "1995 "}, new String [] {"\\{ 1 \}"," 2007 "}};

System. Out. println (replace (STR, object ));

Public static string Replace (final string sourcestring, object [] Object ){
String temp = sourcestring;
For (INT I = 0; I <object. length; I ++ ){
String [] result = (string []) object [I];
Pattern pattern = pattern. Compile (result [0]);
Matcher = pattern. matcher (temp );
Temp = matcher. replaceall (result [1]);
}
Return temp;
}

◆ Query files in a specified directory with regular conditions

// Used to cache the file list
Private arraylist files = new arraylist ();
// Used to carry the file path
Private string _ path;
// It is used to carry the unmerged regular expression.
Private string _ Regexp;

Class myfilefilter implements filefilter {

/**
* Matching file name
*/
Public Boolean accept (File file ){
Try {
Pattern pattern = pattern. Compile (_ Regexp );
Matcher match = pattern. matcher (file. getname ());

Return match. Matches ();
} Catch (exception e ){
Return true;
}
}
}

/**
* Parse the input stream
* @ Param inputs
*/
Filesanalyze (string path, string Regexp ){
Getfilename (path, Regexp );
}

/**
* Analyze the file name and add files
* @ Param Input
*/
Private void getfilename (string path, string Regexp ){
// Directory
_ Path = path;
_ Regexp = Regexp;
File directory = new file (_ path );
File [] filesfile = directory. listfiles (New myfilefilter ());
If (filesfile = NULL) return;
For (Int J = 0; j <filesfile. length; j ++ ){
Files. Add (filesfile [J]);
}
Return;
}

/**
* Display output information
* @ Param out
*/
Public void print (printstream out ){
Iterator elements = files. iterator ();
While (elements. hasnext ()){
File file = (File) elements. Next ();
Out. println (file. getpath ());
}
}

Public static void output (string path, string Regexp ){

Filesanalyze filegroup1 = new filesanalyze (path, Regexp );
Filegroup1.print (system. Out );
}

Public static void main (string [] ARGs ){
Output ("C: \", "[A-z |.] *");
}

Related Article

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.