Re: Regex: Capturing and replacing question
- From: Hal Vaughan <hal@xxxxxxxxxxx>
- Date: Thu, 03 Jan 2008 16:07:11 GMT
Lew wrote:
Hal Vaughan wrote:<http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#appendReplacement(java.lang.StringBuffer
I'm using regexes to find any place in a string where there is a small
letter followed by a capital one and put a space between them. I'm
using "([a-z])([A-Z])" as the pattern to search for and using "$1 $2" as
the replacement string. This is working well in all my tests, but
since I
didn't find it documented where I'd feel safe,
From <http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html>
Groups and capturing
Capturing groups are numbered by counting their opening parentheses from
left to right. In the expression ((A)(B(C))), for example, there are four
such groups:
1 ((A)(B(C)))
2 (A)
3 (B(C))
4 (C)
Group zero always stands for the entire expression.
Hal Vaughan wrote:
Is it correct that $1 in a replacement string references the first
captured
text sequence in the regex? And so on with $2, $3....?
Joshua Cranmer wrote:
The Matcher.appendReplacement says that $1 should be the output of
group(1), so that is correct.
%20java.lang.String)>
The documentation is in the Javadocs for the relevant classes. Javadocs
are
often a great first place to look. The Javadocs are a place where you
will "find it documented" and should be "where [you]'d feel safe" to trust
it.
I goofed on that. I read all the info for Pattern, since that had all the
regex expressions and patterns, then went over the documentation at the
start of Matcher, but I didn't expect to find something like this explained
in the description of a particular method. I also had Googled quite a bit,
but had a high noise-to-signal ratio and kept getting sections that gave
the same general regex explanations. I would think that something like
this should have been in the main part of Pattern or Matcher and not in a
method description.
Hal
.
- Follow-Ups:
- References:
- Regex: Capturing and replacing question
- From: Hal Vaughan
- Re: Regex: Capturing and replacing question
- From: Joshua Cranmer
- Re: Regex: Capturing and replacing question
- From: Lew
- Regex: Capturing and replacing question
- Prev by Date: Re: Accessing grandparent's overridden methods.
- Next by Date: Java Developers / Programmers / Architects Needed for Major Clients in the St. Louis Area!
- Previous by thread: Re: Regex: Capturing and replacing question
- Next by thread: Re: Regex: Capturing and replacing question
- Index(es):
Relevant Pages
|