Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace second occurrence of a character

Tags:

regex

replace

I have some data in the following format:

MM:ss:mmm where MM is minutes, ss is seconds and mmm is 3 digit milliseconds, like:

05:23:236

I'm trying to replace the second occurrence of the colon with a dot:

05:23.236

I'd like to use a regex pattern to do a replace in an editor like Notepad++, I came up with this regex to match my expression:

 \d{1,2}:\d{1,2}:\d{1,3}

But now how can I get only the second occurrence of colon so I can replace it with dot?

EDIT: Notice that the data I'm working with could come with 1-2 digit minute, 1-2 digit second and 1-3 digit millisecond

like image 458
Adolfo Perez Avatar asked Jun 10 '14 12:06

Adolfo Perez


3 Answers

Use this regex:

:(\d{1,3})$

to replace with:

.$1

What above is doing is selecting the last : which is followed by milliseconds by 1-3 digits.

DEMO

like image 157
Amit Joki Avatar answered Sep 30 '22 12:09

Amit Joki


Try this:

  string pattern =  @":(?=\d{3})";
  string input = "your string";
  string replacement = ".";
  Regex rgx = new Regex(pattern);
  string result = rgx.Replace(input, replacement);
like image 30
Moez Rebai Avatar answered Sep 30 '22 12:09

Moez Rebai


your regex was good, you just have to do group and then replace them by calling them again:

selection:

(\d{1,2}:\d{1,2}):(\d{1,3})

replace:

$1\.$2
like image 29
babasLH Avatar answered Sep 30 '22 12:09

babasLH