The regular expression of Android development

Source: Internet
Author: User

EditText the use of regular expressions to check whether the input conforms to the rule

The code is as follows Copy Code

Import Android.app.Activity;

Import Android.os.Bundle;

Import Android.view.View;

Import Android.widget.Button;

Import Android.widget.EditText;

/**

* Class which shows how to validate user input with regular expression

*

* @author Faynasoft Labs

*/

public class Main extends activity {

Private EditText EditText;

Private button button;

@Override

public void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.main);

EditText = (edittext) Findviewbyid (R.id.textid);

Edittext.settext ("edittext element");

Button = (button) Findviewbyid (R.id.btnid);

Button.settext ("Check");

Button.setonclicklistener (New View.onclicklistener () {

@Override

public void OnClick (View v) {

if (Checkstring (Edittext.gettext (). toString ())) {

Edittext.settext ("Corect");

}

}

});

}

/**

* This method checks the if String is correct

* @param s-string which need to check

* @return Value of matching

*/

Private Boolean checkstring (String s) {

Return S.matches ("\w*[.] (Java|cpp|class) ");

}

}

Regular Expression Lookup character

Article Category: Mobile development

String s_result= "distance:2.8km (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.8km (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 expressions to filter special characters

Looking for a long time on the internet and did not find a suitable regular expression to filter special characters; I learned the next, wrote two, to achieve the requirements.

Java Code

Filter special characters

The code is as follows Copy Code

public static string Stringfilter (String str) throws Patternsyntaxexception {

Only letters and numbers are allowed

String regEx = "[^a-za-z0-9]";

Clear out 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^*& Castle () ^$$&*). {}+.|.) %%* (*. Chinese}34{45[]12.FD ' *&999 below is the character ¥ of Chinese ... {}【】。 ,;’“‘”? ";

System.out.println (str);

SYSTEM.OUT.PRINTLN (Stringfilter (str));

}

Filter special characters

  code is as follows copy code
public static String Stringfilter (String str) throws Patternsyntaxexception {//Allow only letters and numbers//String regEx = "[^a-za-z0-9]";//clear out 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^*& Castle () ^$$ &*). {}+.|.) %%* (*. Chinese}34{45[]12.FD ' *&999 below is the character ¥ of Chinese ... {}【】。 ,;’“‘”? "; System.out.println (str); SYSTEM.OUT.PRINTLN (Stringfilter (str)); }

With a JUnit test, of course you can change it to main.

Java regular-expression learning:

Because the regular expression is a very complex system, this example only to mention the concept of getting started, more see the relevant books and explore on their own.

\ back Slash

T interval (' u0009 ')

N Line wrapping (' u000a ')

R carriage return (' u000d ')

The D number is equivalent to [0-9]

D non-numeric equivalent to [^0-9]

s blank symbol [TNX0BFR]

S non-whitespace symbol [^TNX0BFR]

W individual characters [a-za-z_0-9]

W non-individual characters [^a-za-z_0-9]

F Change page character

E Escape

b The boundary of a word

B a non-word boundary

G before the end of a match

^ for limit opening

^java condition is limited to Java-beginning characters

$ for Limit End

The java$ condition is limited to the end of Java character

. Condition limit any single character except N

Java.. Condition is limited to Java after any two characters except for newline

Add a specific restriction condition "[]"

[A-Z] condition is limited to one character in the lowercase a to Z range

[A-Z] condition is limited to one character in the uppercase A to Z range

The [a-za-z] 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

The [0-9a-z] condition is limited to one character in the lowercase 0 to 9 or a to Z range

[0-9[a-z]] condition is limited to one character (intersection) in lowercase 0 to 9 or a to Z range

[] Add in ^ "[^]" again restriction condition

[^a-z] condition is limited to one character in a to Z range of not lowercase

[^a-z] condition is limited to one character in the non-uppercase A to Z range

[^a-za-z] condition is restricted to one character in a to Z range of not lowercase A to Z or uppercase

[^0-9] condition is limited to one character in a non-lowercase 0 to 9 range

[^0-9a-z] condition is limited to one character in the range of non-lowercase 0 to 9 or a to Z

[^0-9[a-z]] condition is limited to one character (intersection) in the range of non-lowercase 0 to 9 or a to Z

You can use the "*" when the limit condition is more than 0 occurrences of a particular character

J* more than 0 J

. * More than 0 arbitrary characters

More than 0 arbitrary characters between J.*d J and D

You can use the "+" when the limit condition is more than 1 occurrences of a particular character

j+ more than 1 J

. + More than 1 arbitrary characters

More than 1 arbitrary characters between J.+d J and D

You can use the "?" when a limit condition is 0 or 1 times the occurrence of a particular character

MAX J or Ja appears

Limit to consecutive occurrences of the specified secondary number character "{a}"

J{2} JJ

J{3} JJJ

Text a more than, and "{a,}"

J{3,} jjj,jjjj,jjjjj,??? (More than 3 times J coexist)

Text above, B below "{a,b}"

j{3,5} JJJ or JJJJ or JJJJJ

Both take a "|"

j| A J or a

java| Hello java or hello

A combination type is specified in "()"

For example, I query <a href= "index.html" >http://www.111cn.net </a> <a href></a> data, can write <a.*href= ". *" > (. +?) </a>

When you use the Pattern.compile function, you can add parameters that control the matching behavior of the regular expression:

Pattern Pattern.compile (String regex, int flag)

The range of values for flag is as follows:

Pattern.canon_eq if and only if the two-character "normal decomposition (canonical decomposition)" is exactly the same, the match is determined. For example, after using this flag, the expression "au030a" matches "?". By default, the specification equality (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 an expression to ignore case matching. To match a Unicode character with an unknown size, just combine the unicode_case with the logo.

Pattern.comments (? x) in this mode, the match is ignored (in the regular expression) empty characters (translator Note: Not the expression in the "\s", but refers to the expression in the Space, tab, enter and so on). Comments start at # until the end of the line. You can enable the UNIX line mode with embedded flags.

Pattern.dotall (? s) in this mode, the expression '. ' You can match any character, including a Terminator that represents a line. By default, an expression '. ' does not match the end character of the line.

Pattern.multiline

(? m) in this mode, ' ^ ' and ' $ ' match the start and end of a row, respectively. Furthermore, ' ^ ' still matches the beginning of the string, ' $ ' also matches the end of the string. By default, these two expressions only match the start and end of a string.

Pattern.unicode_case

(? u) in this mode, if you also enable the Case_insensitive flag, it will match the case of Unicode characters. By default, case insensitive matches are only applicable to the US-ASCII character set.

Pattern.unix_lines (? d) in this mode, only ' n ' is recognized as a row abort and is matched with '. ', ' ^ ', and ' $ '.

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.