-2

i want to extract this pattern from variable String in java (android studio) that always include this pattern but another texts are Variable and don't have same number:

" this internet will expires on 1397/7/16 22:30"

i just want extract YYYY/MM/DD pattern every time

for example give me this: "1397/7/16"

how i can do this?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Logan
  • 13
  • 5

1 Answers1

0

If you just want a simple pattern the gets the numbers resembling a date and time, you could go with something using regular expressions with Pattern and Matcher like this:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestPattern {

    public static void main(String[] args) {
        Pattern datePatt = Pattern.compile(".*(\\d{4}/\\d{1,2}/\\d{1,2})\\s+(\\d{1,2}:\\d{1,3}).*");
        Matcher matcher = datePatt.matcher("this internet will expires on 1397/7/16 22:300");
        if (matcher.matches()) {
            System.out.println(matcher.group(1));
            System.out.println(matcher.group(2));
        }
    }

}

It will print the expected:

1397/7/16
2:300

If you don't know how to use regular expressions, start here: https://www.regular-expressions.info/

And you could test them here: https://www.regexpal.com

If you ever need something more elaborate check this question: Regex to validate date format dd/mm/yyyy

cheers!

wleao
  • 2,316
  • 1
  • 18
  • 17
  • @Logan np! happy coding! if you like it, accept it :) – wleao Dec 03 '17 at 15:21
  • and if i want just extract time , what i must do? – Logan Dec 03 '17 at 15:21
  • use the same strategy, but now the key is using ':' as a delimiter. I'll update the answer – wleao Dec 03 '17 at 15:22
  • remember that regexp is powerful but also dangerous! Before using it in production code, make sure your regexp is matching what you have available in your texts. There will always be surprises! – wleao Dec 03 '17 at 15:25