GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Main Page
  • Help
  • Browse
  • Cookbook
  • Wikijunior
  • Featured books
  • Recent changes
  • Special pages
  • Random book
  • Using Wikibooks
  • Reading room forum
  • Community portal
  • Help out!
  • Policies and guidelines

This view

  • Original page
  • New address

GeezerVison is showing en.wikibooks.org — Regular Expressions - Wikibooks, open books for an open world

< Java Programming

Navigate Advanced topic:
  • Networking
  • Database programming
  • Regular Expressions
  • Libraries, extensions and frameworks
  • 3D programming
  • Java Native Interface
  • Invoking C
  • Foreign Function and Memory API
  • Byte Code


The regular expressions (regex) are provided by the package java.util.regex.

Researches

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:

import java.util.regex.Pattern;
public class Regex {
	public static void main(String[] args) {
		String s = "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:

  1. find(): find the next result.
  2. group(): displays the result.

For example, this script displays the HTML b tags contents:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Regex {
	public static void main(String[] args) {
		String s = "Test <i>Java</i> <b>regex</b> for <b>Wikibooks</b>.";
		Pattern p = Pattern.compile("<b>([^<]+)</b>");
		Matcher m = 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

This section is a stub.
You can help Wikibooks by expanding it.
Retrieved from "https://en.wikibooks.org/w/index.php?title=Java_Programming/Regular_Expressions&oldid=3675904"
Categories:
  • Book:Java Programming
  • Section stubs
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.