1

This is the input format:

<1> today is <2> current time is <3> humidity is <4>

I want to use Java Regex to get <1> ,<2>, <3> and <4>.

e.g if the input is

Hello today is 03/17 current time is 03:20 humidity is 50% 

I want to get Hello, 03/17, 03:20 and 50%

Can anyone help show me what Regex should be?

4
  • 1
    What have you tried so far? Will the string always look like this? What's the maximum size of each field? There are more details needed for this. Commented Jan 18, 2017 at 6:16
  • @EvanKnowlesThanks Evan. I have updated the question. Commented Jan 18, 2017 at 6:25
  • Is it a fixed pattern? Commented Jan 18, 2017 at 6:36
  • @sameerasy Yes, it's fixed pattern. but value of <1>,<2>..<4> can be any string. Commented Jan 18, 2017 at 6:44

1 Answer 1

4

Update:

You can use a matcher with a regex to extract out the various pieces of the template input sentence which you expect.

String input = "Hello today is 03/17 current time is 03:20 humidity is 50%";
Pattern p = Pattern.compile("(.*) today is (.*) current time is (.*) humidity is (.*)");
Matcher m = p.matcher(input);
if (m.find()) {
        System.out.println("Found greeting: " + m.group(1));
        System.out.println("Found date: " + m.group(2));
        System.out.println("Found time: " + m.group(3));
        System.out.println("Found humidity: " + m.group(4));
}

Output:

Found greeting: Hello
Found date: 03/17
Found time: 03:20
Found humidity: 50%

Note that capture groups begin at index 1, not 0, because m.group(0) returns the entire original string against which the regex is being applied.

Below is my original answer, which was given before you updated your question:

One simple approach would be to just split the sentence by whitespace, and then retain any terms which have at least one number in them:

String input = "Hello today is 01/17 current time is 03:20 humidity is 50%.";
String[] parts = input.split("\\s+");
for (String part : parts) {
    if (part.matches(".*\\d+.*")) {
        System.out.println(part);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.