Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you capture and reuse a match with Java regex?

Tags:

java

regex

I'm trying to remember the correct notation for doing find-replace regex matches in Java.

Say I have the string

    String s = "My name is ''Eric'' and I have a bee called ''Eric'' 
and a fish called ''Wanda''."

I want to do something like the following:

s.replaceAll("\'\'$$\'\'", "$$");

To give: My name is Eric and I have a bee called Eric and a fish called Wanda.

But I know $$ isn't the correct notation to capture whatever is in the '' and use it to replace the found match.

What's the particular notation I'm looking for here?

Thanks in advance.

-Dave.

like image 224
f1dave Avatar asked May 19 '11 11:05

f1dave


People also ask

What does capture mean in regex?

capturing in regexps means indicating that you're interested not only in matching (which is finding strings of characters that match your regular expression), but you're also interested in using specific parts of the matched string later on.

How do I capture a word in regex?

To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.

How do I use regex to match?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How does Java regex work?

It works as the combination of compile and matcher methods. It compiles the regular expression and matches the given input with the pattern. splits the given input string around matches of given pattern. returns the regex pattern.


1 Answers

s.replaceAll("\'\'(.*?)\'\'", "$1");
like image 113
netbrain Avatar answered Nov 07 '22 01:11

netbrain