dushkin
dushkin

Reputation: 2101

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

Upvotes: 2

Views: 94

Answers (1)

anubhava
anubhava

Reputation: 785108

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

Upvotes: 4

Related Questions