Skip to content
Advertisement

Java: Extracting a specific REGEXP pattern out of a string

How is it possible to extract only a time part of the form XX:YY out of a string?

For example – from a string like:

sdhgjhdgsjdf12:34knvxjkvndf, I would like to extract only 12:34.

( The surrounding chars can be spaces too of course )

Of course I can find the semicolon and get two chars before and two chars after, but it is bahhhhhh…..

Advertisement

Answer

You can use this look-around based regex for your match:

(?<!d)d{2}:d{2}(?!d)

RegEx Demo

In Java:

Pattern p = Pattern.compile("(?<!\d)\d{2}:\d{2}(?!\d)");

RegEx Breakup:

(?<!d)  # negative lookbehind to assert previous char is not a digit
d{2}    # match exact 2 digits
:        # match a colon
d{2}    # match exact 2 digits
(?!d)   # negative lookahead to assert next char is not a digit

Full Code:

Pattern p = Pattern.compile("(?<!\d)\d{2}:\d{2}(?!\d)");
Matcher m = pattern.matcher(inputString);

if (m.find()) {
    System.err.println("Time: " + m.group());
}

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement