|
Blog
Home
Articles/Links
Mugs, T-shirts
Comments/Raves
New in 1.5.3
A Game
An Online Test
Questions
Copyright/License
Download Free
If you need a non-LGPL version
You Can Buy!
Online help...
Quick Start
Tutorial Part 1
Tutorial Part 2
Tutorial Part 3
Tutorial Part 4
Tutorial Part 5
Tutorial Part 6
Examples
Support
FAQ
Documentation
Useful apps...
Java Beautifier
Code Colorizer
GUI Grep
Swing Grep
Other stuff...
Phreida
xmlser
 |
Tutorial Part 3
Pattern Elements
\A, \Z, ^, $, \b, \B
There pattern elements "^" and "\A" matches the beginning of a String.
Regex r = new Regex("^.....");
r.search("Hello world.");
System.out.println(r.stringMatched());
// Prints "Hello"
r.search(" Hello world.");
System.out.println(r.didMatch());
// Prints "false"
|
Likewise, the pattern element "$" or "\Z" matches the end of
a String.
Regex r = new Regex(".......$");
r.search("Say goodbye");
System.out.println(r.stringMatched());
// Prints "goodbye"
|
You may, however, be interested in matching on a
different sort of boundary, a "word boundary." This
is the sort of thing you search for when you select
a "match whole word" option from a search dialog
box in a word processor. For example, suppose you
wish to match on the word "some" but not words like
"somehow" or "twosome."
Regex r = new Regex("\\bsome\\b");
r.search("somehow");
System.out.println(""+r.didMatch());
// Prints "false"
r.search("twosome");
System.out.println(""+r.didMatch());
// Prints "false"
r.search("some");
System.out.println(""+r.didMatch());
// Prints "true"
|
The "\\b" pattern element matches on the space
between a word character ("\\w" or "[a-zA-Z0-9_]")
or a non-word character ("\\W" or "[^a-zA-Z0-9_]").
It will also match on the beginning or end of a
String.
There is also a "\\B" that will fail to match on a
boundary that is a word boundary. In this example
we want to match on a word that begins with the word
word "some" but does not include the word "some."
Regex r = new Regex("\\bsome\\B");
r.search("somehow");
System.out.println(""+r.didMatch());
// Prints "true"
r.search("twosome");
System.out.println(""+r.didMatch());
// Prints "false"
r.search("some");
System.out.println(""+r.didMatch());
// Prints "false"
|
Previous
Next
|