I'm performing a test to find and replace a string of 3 or 4 capital letters followed by a number with that same string, a hyphen, and that same number. In Perl, I can use:
s/([A-Z]{3,4})([0-9])/$1-$2/g;
I've tried this in Java, hardcoding a string like:
public class Test {
public static void main(String[] args) {
String test = "TEST1";
Pattern p = Pattern.compile("([A-Z]{3,4})([0-9])");
Matcher m = p.matcher(test);
if (m.find()) {
m.replaceAll(m.group(1) + "-" + m.group(2));
}
System.out.println(test);
}
}
But no match was found. Is my Java syntax wrong or is it a regular expression issue?
use "\p{Pd}" without quotes to match any type of hyphen. The '-' character is just one type of hyphen which also happens to be a special character in Regex.
Regular expressions can be used to perform all types of text search and text replace operations. Java does not have a built-in Regular Expression class, but we can import the java.util.regex package to work with regular expressions.
Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".
No need to use Pattern/Matcher, you can just do:
test = test.replaceAll( "([A-Z]{3,4})([0-9])", "$1-$2");
You just need to use a replaceAll
with the regex you already have:
String test = "TEST1";
System.out.println(test.replaceAll("([A-Z]{3,4})([0-9])", "$1-$2"));
See IDEONE demo
This is from docs:
public String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With