简体   繁体   中英

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

Expected String: 2017-02-15T12:00:00+00:00

Expected String removes everything in milliseconds.

My regex pattern looks like this: (:[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) .

The backslash will force the match with the '.' char, instead of any char, which is what the dot represents in a regex.

The (?: defines a non-capturing group, so it will not be considered in the group(...) on the matcher.

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

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 :

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 .

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. Since you only have one pair of unescaped parentheses (1 capturing group) the ID of the group is 1.

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

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

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.

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