Flukey
Flukey

Reputation: 6555

regex pattern - extract a string only if separated by a hyphen

I've looked at other questions, but they didn't lead me to an answer.

I've got this code:

Pattern p = Pattern.compile("exp_(\\d{1}-\\d)-(\\d+)");

The string I want to be matched is: exp_5-22-718

I would like to extract 5-22 and 718. I'm not too sure why it's not working What am I missing? Many thanks

Upvotes: 0

Views: 1618

Answers (4)

hoaz
hoaz

Reputation: 10153

Try this one:

Pattern p = Pattern.compile("exp_(\\d-\\d+)-(\\d+)");

In your original pattern you specified that second number should contain exactly one digit, so I put \d+ to match as more digits as we can. Also I removed {1} from the first number definition as it does not add value to regexp.

Upvotes: 1

Parvin Gasimzade
Parvin Gasimzade

Reputation: 26012

You can use the string.split methods to do this. Check the following code. I assume that your strings starts with "exp_".

    String str = "exp_5-22-718";
    if (str.contains("-")){
        String newStr = str.substring(4, str.length());
        String[] strings = newStr.split("-");

        for (String string : strings) {
            System.out.println(string);
        }
    }

Upvotes: 1

bellum
bellum

Reputation: 3710

In your regexp you missed required quantifier for second digit \\d. This quantifier is + or {2}.

    String yourString = "exp_5-22-718";

    Matcher matcher = Pattern.compile("exp_(\\d-\\d+)-(\\d+)").matcher(yourString);
    if (matcher.find()) {
        System.out.println(matcher.group(1)); //prints 5-22
        System.out.println(matcher.group(2)); //prints 718
    }

Upvotes: 1

Jason McCreary
Jason McCreary

Reputation: 72971

If the string is always prefixed with exp_ I wouldn't use a regular expression.

I would:

Note: This answer is based on the assumptions. I offer it as a more robust if you have multiple hyphens. However, if you need to validate the format of the digits then a regular expression may be better.

Upvotes: 1

Related Questions