Logic1 Logic1 - 1 year ago 150
Android Question

Regex for matching multiple date formats?

Sorry if this is a noob question but I'm not very comfortable with regex and (as of now) this is a little beyond my understanding.

My dilemma is that we have a verity of ID badges that get scanned into an android application and I'm trying to parse out some dates.

For example, some dates are represented like so:

"ISS20141231" format = yyyyMMdd desired output = "20141231"
"ISS12312014" format = MMddyyyy desired output = "12312014"
"ISS12-31-2014" format = MM-dd-yyyy desired output = "12312014"

currently I have a regex pattern:

Pattern p = Pattern.compile("ISS(\\d{8})");
Matcher m = p.matcher(scanData);

which worked fine for the first two examples but recently I have realized that we also occasionally have dates which use dashes (or slashes) as separators.

Is there an efficient means for extracting these dates without having to write multiple patterns and loop through each one checking for a match?

possibly similar to: "ISS([\d{8} (\d{2}\w\d{2}\w\d{4}) (\d{4}\w\d{2}\w\d{2})])"


Just to make things a little bit more clear. Whit I am trying to match is a substring of a much larger string. ISSMMddyyyy could be located anywhere within the original string So regex must search for and find the match.

Answer Source

If that date string is actually a substring of a larger string, and so you need the regex in order to also search for that pattern, you could modify your regex to be:


And then when retrieving the capture group, strip the hyphens and slashes.

String dateStr = m.group(1).replaceAll("[/-]", "");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download