How to replace characters '-' using regular expressions?
There some date or datetime fields in my json string and they all use character '/' as separator, such as '2016/10/10 10:10:10' .
now i need the date or datetime fields with this form '2016-10-10 10:10:10' .
For example:
{
"code": "200",
"error": "",
"total": "10",
"page": "1",
"result": [
{
"CustomerNo": "0432215",
"Name": "ACE-Dick/USA",
"LastUpdatedDate": "2015/08/07 13:25:32",
"LastUpdatedBy": "System"
}
]
}
The text below is correct json what i want.
{
"code": "200",
"error": "",
"total": "10",
"page": "1",
"result": [
{
"CustomerNo": "0432215",
"Name": "ACE-Dick/USA",
"LastUpdatedDate": "2015-08-07 13:25:32",
"LastUpdatedBy": "System"
}
]
}
I can find the date string using regular expresion as follow,but how can replace it?
\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}
Use capturing groups around the values you need to keep, and just match what you need to replace:
(\d{4})/(\d{2})/(\d{2} \d{2}:\d{2}:\d{2})
^ -1- ^ ^ -2- ^ ^ --------- 3---------- ^
and replace with $1-$2-$3
where $1
is a backreference to the value captured with Group 1, $2
references Group 2 value, etc.
See the regex demo
String s = "2016/10/10 10:10:10";
String rx = "(\\d{4})/(\\d{2})/(\\d{2} \\d{2}:\\d{2}:\\d{2})";
System.out.println(s.replaceAll(rx, "$1-$2-$3"));
See more on capturing groups and backreferences here .
You can do grouping and substitution, the syntax will vary according to the language you are using. For grouping you can use (\\d{4})/(\\d{2})/(\\d{2} \\d{2}:\\d{2}:\\d{2}) for substitution just use $1,$2,$3 to reference these groups while substituting.
If you have your date as a String, you can use replaceAll()
Example
yourString.replaceAll("/", "-")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.