Match & Replace NSString using Regex
In this example shows, to display current date in a label in a specific format (e.g. 31/12/14 12:59PM)
You can see the date format
There is no such a format for 2 characters year, so we need to replace through regex.
1 | // 1. |
- Specify the date format (e.g. the result will be 31/12/2014 12:59PM), and select current date to display
- Pass the format to the formatter, and store the date as string
- We know that there is only 1 consecutive 4 integers in the string, so we want to extract it. The braces
()
here is to capture the matches text. Double back slash\\
here is to escape the back slash (as we know it is
special character) - Now we match the whole date string (so we specify the range from index 0 to the string length) from the regex
- We get the matched string now (i.e.
2014
in this case), then we replace the characters in the range
(i.e.(6, 4)
which is the index for2014
) with the last 2 characters of2014
- Finally we set the value to the label