简体   繁体   English

如何使用正则表达式替换字符?

[英]How to replace characters using regular expressions?

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' . 我的json字符串中有一些日期或日期时间字段,它们都使用字符'/'作为分隔符,例如'2016/10/10 10:10:10'
now i need the date or datetime fields with this form '2016-10-10 10:10:10' . 现在我需要这种格式为'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. 下面的文本是我想要的正确json。

{
 "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} \\ 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. 并替换为$1-$2-$3 ,其中$1是对第1组捕获的值的反向引用, $2引用第2组的值,依此类推。

See the regex demo 正则表达式演示

Java demo : Java演示

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. 对于分组,您可以使用(\\ d {4})/(\\ d {2})/(\\ d {2} \\ d {2}:\\ d {2}:\\ d {2})进行替换,只需使用$ 1 ,$ 2,$ 3来代替这些组。

If you have your date as a String, you can use replaceAll() 如果您将日期作为字符串,则可以使用replaceAll()

Example

yourString.replaceAll("/", "-")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM