Reputation: 197
Is there a way to check if there is a regex match and then perform a substitution on part of the match?
Ex. -> "a3c" if "[1-9]c$" -> "a3" (if there is a "NUMc" at the end take off the "c")
specifically trying to generate a mapping a rules in to perform operations such as:
rule.put(String regex, String replacement)
rule.put("[1-9]c$","");
to be able to call:
"a3c".replace(rule.key,rule.value) //delete just the "c" not the whole "3c".
Also I know that i can make an if statement to check if it matches and then call a replacement but i want to see if there is a neat one liner :)
Upvotes: 0
Views: 51
Reputation: 3405
Regex: (\\d+)c$
Substitution: $1
Details:
()
Capturing group\d
Matches a digit (equal to [0-9]
)+
Matches between one and unlimited times$
Asserts position at the end of the string$1
Group 1.Java code:
String text = "a3c";
text = text.replaceAll("(\\d+)c$", "$1");
System.out.print(text); // a3
Upvotes: 2