简体   繁体   中英

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

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.

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.

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
    }

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);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM