Regular Expressions
Appearance
From Wikibooks, open books for an open world
Navigate Advanced topic: ()
- 25% developed as of Dec 19, 2012 Networking
- 25% developed as of Dec 19, 2012 Database programming
- 25% developed as of Jan 30, 2016 Regular Expressions
- 25% developed as of Dec 19, 2012 Libraries, extensions and frameworks
- 25% developed as of Dec 19, 2012 3D programming
- 75% developed as of Fev 27, 2013 Java Native Interface
- 75% developed as of Nov 20, 2013 Invoking C
- 50% developed as of Nov 20, 2013 Byte Code
The regular expressions (regex) are provided by the package java.util.regex
.
Researches
[edit | edit source ]The Pattern class offers the function matches which returns true if an expression is found into a string.
For example, this script returns the unknown word preceding a known word:
importjava.util.regex.Pattern; publicclass Regex{ publicstaticvoidmain(String[]args){ Strings="Test Java regex for Wikibooks."; System.out.println(Pattern.matches("[a-z]* Wikibooks",s)); } } // Displays: "for Wikibooks"
The Matcher class allows to get all matches for a given expression, with different methods:
- find(): find the next result.
- group(): displays the result.
For example, this script displays the HTML b tags contents:
importjava.util.regex.Pattern; importjava.util.regex.Matcher; publicclass Regex{ publicstaticvoidmain(String[]args){ Strings="Test <i>Java</i> <b>regex</b> for <b>Wikibooks</b>."; Patternp=Pattern.compile("<b>([^<]+)</b>"); Matcherm=p.matcher(s); while(m.find()){ System.out.println(m.group()); System.out.println(m.group(1)); } } } /* Displays: <b>regex</b> regex <b>Wikibooks</b> Wikibooks */
Replacements
[edit | edit source ]This section is a stub.
You can help Wikibooks by expanding it.
You can help Wikibooks by expanding it.