简体   繁体   English

在正则表达式模式中匹配后删除匹配器的一部分

[英]remove part of matcher after the match in regex pattern

I need to help in writing regex pattern to remove only part of the matcher from original string. 我需要帮助编写正则表达式模式,以从原始字符串中仅删除部分匹配器。

Original String: 2017-02-15T12:00:00.268+00:00 原始字符串: 2017-02-15T12:00:00.268+00:00

Expected String: 2017-02-15T12:00:00+00:00 预期字符串: 2017-02-15T12:00:00+00:00

Expected String removes everything in milliseconds. Expected String以毫秒为单位删除所有内容。

My regex pattern looks like this: (:[0-5][0-9])\\.[0-9]{1,3} 我的正则表达式模式如下所示: (:[0-5][0-9])\\.[0-9]{1,3}

i need this regex to make sure i am removing only the milliseconds from some time field, not everything that comes after dot. 我需要这个正则表达式,以确保我从一些时间字段中删除只有毫秒,而不是点后面的所有内容。 But using above regex, I am also removing the minute part. 但是使用上面的正则表达式,我也删除了分钟部分。 Please suggest and help. 请提出建议和帮助。

Change your pattern to (?::[0-5][0-9])(\\.[0-9]{1,3}) , run the find in the matcher and remove all it finds in the group(1) . 将您的模式更改为(?::[0-5][0-9])(\\.[0-9]{1,3}) ,在匹配器中运行find并删除group(1)找到的所有内容group(1)

The backslash will force the match with the '.' 反斜杠将强制匹配'。' char, instead of any char, which is what the dot represents in a regex. char,而不是任何char,这是正则表达式中的点所代表的。

The (?: defines a non-capturing group, so it will not be considered in the group(...) on the matcher. (?:定义一个非捕获组,因此不会在匹配器的group(...)考虑它。

And adding a parenthesis around what you want will make it show up as group in the matcher, and in this case, the first group. 并在您想要的内容周围添加括号将使其在匹配器中显示为组,在本例中为第一组。

A good reference is the Pattern javadoc: http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html 一个很好的参考是模式javadoc: http//docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

You have defined a capturing group with (...) in your pattern, and you want to have that part of string to be present after the replacement is performed. 您已在模式中定义了一个带有(...)捕获组 ,并且您希望在执行替换后将该部分字符串存在。 All you need is to use a backreference to the value stored in this capture. 您只需要对此捕获中存储的值使用反向引用 It can be done with $1 : 它可以用$1来完成:

String s = "2017-02-15T12:00:00.268+00:00";
String res = s.replaceFirst("(:[0-5][0-9])\\.[0-9]{1,3}", "$1");
System.out.println(res); // => 2017-02-15T12:00:00+00:00

See the Java demo and a regex demo . 请参阅Java演示正则表达式演示

The $1 in the replacement pattern tells the regex engine it should look up the captured group with ID 1 in the match object data. 替换模式中的$1告诉正则表达式引擎它应该在匹配对象数据中查找ID为1的捕获组。 Since you only have one pair of unescaped parentheses (1 capturing group) the ID of the group is 1. 由于您只有一对未转义的括号(1个捕获组),因此该组的ID为1。

使用$ 1和$ 2变量进行替换

string.replaceAll("(.*)\\.\\d{1,3}(.*)","$1$2");

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

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