2

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

1 Answer 1

4

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());
}
Sign up to request clarification or add additional context in comments.

9 Comments

Looks great! But how can I extrat the time out of the string with that? Thank you!
Use Matcher class in Java and call p.matcher followed by matcher.find and matcher.group to get your value
Yes! I managed to find this solution already! thank you so much!
That's great, I've also provide full code in answer for reference.
ideone.com/2EzLIz - no space addition is necessary, lookarounds do not consume characters.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.