Regular expression capture groups versus using date separation, which is better?

In several cases, I needed to fix the "day" part of the date, formatted as follows: "YYYY/DD/MM"My question is whether it was better to use a regular expression with a capture group vs. just calling split on "/" and just taking the second element in the array?

Functionally, I understand that BOTH gets the same result.

In my opinion, I understand that they use the regex mechanism under the hood, and that in most cases I just drop the array after reading the value for the day using split. But technically, I do the same after reading from the object Match. I am looking to see if there are any corner cases and trade-offs that I have to consider, but I do not? (In addition, readability ... the “split” clearly wins there ...)

=== EDIT === By API I am limited to Groovy 1.5.0 for silly reasons.

To clarify edmastermind solution:

def nowCal = Calendar.instance 
def currentDay = nowCal.get(Calendar.DAY_OF_MONTH)
+3
source share
6 answers

In Groovy, you can simply:

def date = '2012/05/25'

assert 25 == Date.parse( 'yyyy/MM/dd', date )[ Calendar.DAY_OF_MONTH ]

For Groovy 1.5.0 this will be (wrapped as a function):

int getDay( String date, String format='yyyy/MM/dd' ) {
  Calendar.instance.with {
    time = new java.text.SimpleDateFormat( format ).parse( date )
    get( Calendar.DAY_OF_MONTH )
  }
}

def date = '2012/05/25'
assert 25 == getDay( date )
+2
source

, String, , . REGEX , .

+2

, DateFormat, setDateFormat , Date. , , .

, :
, , .
, DateFormat .

+2

, , .split .

. , . , , , .

.split("//") , , , , , .

+1

, String # indexOf String #. , .

, , , , , split return, .

, . DateFormat. , .

+1

java-, DAY_OF_MONTH, "" ?

+1

All Articles