Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting hyphen between groups with Java regex issue

Tags:

java

regex

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?

like image 520
David M Avatar asked Jun 30 '15 20:06

David M


People also ask

How do you do a hyphen in Regex?

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.

Does Regex work in Java?

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.

WHAT IS group in Regex Java?

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".


2 Answers

No need to use Pattern/Matcher, you can just do:

test = test.replaceAll( "([A-Z]{3,4})([0-9])", "$1-$2");
like image 129
anubhava Avatar answered Oct 11 '22 13:10

anubhava


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.

like image 28
Wiktor Stribiżew Avatar answered Oct 11 '22 13:10

Wiktor Stribiżew