Java Regex Replace with Capturing Group

Java Regex Replace with Capturing Group

How about:

if (regexMatcher.find()) {
resultString = regexMatcher.replaceAll(
String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}

To get the first match, use #find(). After that, you can use #group(1) to refer to this first match, and replace all matches by the first maches value multiplied by 3.

And in case you want to replace each match with that match's value multiplied by 3:

    Pattern p = Pattern.compile("(\\d{1,2})");
Matcher m = p.matcher("12 54 1 65");
StringBuffer s = new StringBuffer();
while (m.find())
m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
System.out.println(s.toString());

You may want to look through Matcher's documentation, where this and a lot more stuff is covered in detail.

Replace group 1 of Java regex with out replacing the entire regex

You need to use the following pattern with capturing groups:

(\w*)lan(\w+)
^-1-^ ^-2-^

and replace with $1<--->$2

See the regex demo

The point is that we use a capturing group around the parts that we want to keep and just match what we want to discard.

Java demo:

String str = "plan plans lander planitia";
System.out.println(str.replaceAll("(\\w*)lan(\\w+)", "$1<--->$2"));
// => plan p<--->s <--->der p<--->itia

If you need to be able to replace the Group 1 and keep the rest, you may use the replace callback method emulation with Matcher#appendReplacement:

String text = "plan plans lander planitia";
String pattern = "\\w*(lan)\\w+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(0).replaceFirst(Pattern.quote(m.group(1)), "<--->"));
}
m.appendTail(sb); // append the rest of the contents
System.out.println(sb.toString());
// output => plan p<--->s <--->der p<--->itia

See another Java demo

Here, since we process a match by match, we should only replace the Group 1 contents once with replaceFirst, and since we replace the substring as a literal, we should Pattern.quote it.

Java String.replaceAll() with back reference

I'll try to explain what's happening in regex.

str.replaceAll("(^\\*)|(\\*$)|\\*", "$1$2");

$1 represents first group which is (^\\*)
$2 represents 2nd group (\\*$)

when you call str.replaceAll, you are essentially capturing both groups and everything else but when replacing, replace captured text with whatever got captured in both groups.

Example: *abc**def* --> *abcdef*

Regex is found string starting with *, it will put in $1 group, next it will keep looking until it find * at end of group and store it in #2. now when replacing it will eliminate all * except one stored in $1 or $2

For more information see Capture Groups

Is there a way to replace only one captured group in java matcher regex?

You can keep some groups of your regex and replace others in the occurences found in a string . if we suppose that your regex is : [\\s,\\(](%variable)[\\s,$] , then you can use the replaceAll() method of java.lang.String.
You need first to set your regex in the form of saparate groups

ex:([\\s,\\(])(%variable)([\\s,$]),
so you have

The 1st group is : [\\s,\\(]

The second group is %variable

And the third group is [\\s,$] , now you can set reference of your groups the
final value that will replace each occurence found in your regex ,for example if we want to replace the second group with the string 'myNewVal' the code will be :

String myRegex = "([\\s,\\(])(%variable)([\\s,$])";
String replacedValue = originalValue.replaceAll(myRegex,"$1myNewVal$3");

$1 and $3 refer to the first and the third group, we keep them in the replaceValue.

if you want just remove the second group you can try this :

String myRegex = "([\\s,\\(])(%variable)([\\s,$])";
String replacedValue = originalValue.replaceAll(myRegex,"$1$3");

Can I replace groups in Java regex?

Use $n (where n is a digit) to refer to captured subsequences in replaceFirst(...). I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group.

Pattern p = Pattern.compile("(\\d)(.*)(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
// replace first number with "number" and second number with the first
String output = m.replaceFirst("number $3$1"); // number 46
}

Consider (\D+) for the second group instead of (.*). * is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (\d) has nothing to match, before it can match to the final digit.

Java Regex Replace with Capturing Group

The definitive solution to this problem was posted by Elliott Hughes on his blog a couple years ago. Elliott keeps introducing pointless dependencies to other classes in the online version, so I'll post a stand-alone version here (the dependencies are only in the tests in the main() method).

import java.util.regex.*;

/**
* A Rewriter does a global substitution in the strings passed to its
* 'rewrite' method. It uses the pattern supplied to its constructor, and is
* like 'String.replaceAll' except for the fact that its replacement strings
* are generated by invoking a method you write, rather than from another
* string. This class is supposed to be equivalent to Ruby's 'gsub' when
* given a block. This is the nicest syntax I've managed to come up with in
* Java so far. It's not too bad, and might actually be preferable if you
* want to do the same rewriting to a number of strings in the same method
* or class. See the example 'main' for a sample of how to use this class.
*
* @author Elliott Hughes
*/
public abstract class Rewriter
{
private Pattern pattern;
private Matcher matcher;

/**
* Constructs a rewriter using the given regular expression; the syntax is
* the same as for 'Pattern.compile'.
*/
public Rewriter(String regex)
{
this.pattern = Pattern.compile(regex);
}

/**
* Returns the input subsequence captured by the given group during the
* previous match operation.
*/
public String group(int i)
{
return matcher.group(i);
}

/**
* Overridden to compute a replacement for each match. Use the method
* 'group' to access the captured groups.
*/
public abstract String replacement();

/**
* Returns the result of rewriting 'original' by invoking the method
* 'replacement' for each match of the regular expression supplied to the
* constructor.
*/
public String rewrite(CharSequence original)
{
this.matcher = pattern.matcher(original);
StringBuffer result = new StringBuffer(original.length());
while (matcher.find())
{
matcher.appendReplacement(result, "");
result.append(replacement());
}
matcher.appendTail(result);
return result.toString();
}

public static void main(String... args) throws Exception
{
String str = "12 54 1 65";

// anonymous subclass
Rewriter tripler = new Rewriter("(\\d{1,2})")
{
public String replacement()
{
int intValue = Integer.valueOf(group(1));
return String.valueOf(intValue * 3);
}
};
System.out.println(tripler.rewrite(str));

// inline subclass
System.out.println(new Rewriter("(\\d{1,2})")
{
public String replacement()
{
int intValue = Integer.valueOf(group(1));
return String.valueOf(intValue * 3);
}
}.rewrite(str));

}
}

Replace Java Regex Capture Groups with Parts of Themselves

Use

https://www.tutorialspoint.com/java/java_string_replaceall.htm

and do something like

a.replaceAll("\\[\\[(\\w+)[^\\[]+\\]\\]", "$1");

Java String.replaceAll() refer the latest found group

s.replaceAll("(a+)", "$1\n") should work:

jshell> String s = "aaabbbaa"
s ==> "aaabbbaa"

jshell> s.replaceAll("(a+)", "$1\n")
$2 ==> "aaa\nbbbaa\n"

As pointed out in the comments already, you'll have to mark the capture group in your regular expression. That's what the parentheses (...) do. Then you'll have to reference that capture group with $1, which is the first capture group. $0 would be the whole match (also pointed out in the comments), but just $ will not work.

Java String replace - non-capturing group captures

You can actually do what you wanted using capturing groups. Here it captures the part you want to keep and replaces the whole string. The $1 is a back reference to the capture group.

 System.out.println(
initial.replaceAll("\\d{3}-\\d{3}(\\-\\d{4})", "XXX-XXX$1"));

And I presume you realize that if the regex doesn't match, then the original string is returned with no changes.

Java replace capturing group with different value

Please consider bookmarking the Stack Overflow Regular Expressions FAQ for future reference. There's a bunch of Java-specific information in there, particularly in the "Flavor-Specific Information" section.


This works:

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

public class Replacement {
public static final void main(String[] ignored) {

String str = "fname:hello hello:world ffff:off";
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("fname", "meme");
mapping.put("hello", "below");
mapping.put("ffff", "ssss");
Pattern pat = Pattern.compile("([a-zA-Z_]+):");

Matcher m = pat.matcher(str);

StringBuffer sb = new StringBuffer();
while(m.find()) {
String rplcWith = mapping.get(m.group(1));
m.appendReplacement(sb, rplcWith + ":");
}
m.appendTail(sb);

System.out.println(sb);
}
}

Output:

[C:\java_code\]java Replacement
meme:hello below:world ssss:off


Related Topics



Leave a reply



Submit