I have the following question about Java Regular expression.
When I am defining a regular expression using pattern:
String pattern = "(\\d{4})\\d{2}\\d{2}";
and the input string is "20180808"
,
I can get the group(0)
- 20180808
but
group(1)
- not match
group (2)
- 08
group (3)
- 08
,
I am sure the regular expression can be effective in other languages, like Python, C#.
Can anyone Help? thanks for your expert solution.
@Test
public void testParseDateStringToMinimumOfTheDate() {
try {
UtilsFactory utilsFactory = UtilsFactory.getInstance();
DateUtils dateUtils = utilsFactory.getInstanceOfDateUtils();
CalendarUtils calendarUtils = utilsFactory.getInstanceOfCalendarUtils();
calendarUtils.parseDateStringToMinimumOfTheDate("20180808");
} catch (Exception e) {
e.printStackTrace();
}
}
public Calendar parseDateStringToMinimumOfTheDate(String dateString_yyyyMMdd) throws Exception {
Calendar cal = null;
String pattern = "(\\d{4})\\d{2}\\d{2}";
try {
cal = getMaxUtcCalendarToday();
List<String> matchStringList = regMatch(dateString_yyyyMMdd, pattern);
for (int i = 0; i < matchStringList.size(); i++) {
}
} catch (Exception e) {
logger.error(getClassName() + ".parseDateStringToBeginningOfTheDate()- dateString_yyyyMMdd="
+ dateString_yyyyMMdd, e);
throw e;
}
return cal;
}
private List<String> regMatch(String sourceString, String patternString) throws Exception {
List<String> matchStrList = null;
Pattern pattern = null;
Matcher matcher = null;
try {
matchStrList = new ArrayList<String>();
pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(sourceString);
while (matcher.find()) {
matchStrList.add(matcher.group());
}
} catch (Exception e) {
logger.error(
getClassName() + ".regMatch() - sourceString=" + sourceString + ",patternString=" + patternString,
e);
throw e;
}
return matchStrList;
}