Search code examples
c#.netregexvisual-studiovisual-studio-2022

Add space after specified data using regular expression in Visual Studio


As we all know, Visual Studio has very powerful text editing functions. Now there are hundreds of thousands of data in my txt file. I made a wrong operation, which caused some problems with the data.

The original date format should be like this yyyy-mm-dd hh-mm-ss, but I accidentally deleted the space and it became yyyy-mm-ddhh-mm-ss. Here are some of my data:

20240605092318,20240605092318,2.913750.2345169718,18,2024-05-0108:49:15
20240605092318,20240605092318,2.913580.2405169918,18,2024-04-2210:38:58
20240605092318,20240605092318, 2.919230.2394170218,18,2024-01-2510:10:16
20240605092318,20240605092318,2.916530.2319170518,18,2024-03-0717:25:09
20240605092318,20240605092318,2.918290.2387170618,18,2024-05-2313:55:14

Yes, now I want to add a space between "year-month-day" and "hour-minute-second", please pay attention to the last set of data in each row.

I tried to add spaces using regular expressions in the text editor of Visual Studio. Here is the regular expression I used, but it doesn't work

\d{4}-\d{2}-\d{2}$

enter image description here

Can anyone tell me what the problem is?


Solution

  • Dollar sign ($) matches the end of the string, and your strings end with hour and not date - \d{2}:\d{2}:\d{2}$ would be a match to your time section of the string.

    Adding the space with code would require adding a space at the position - however, if the goal is to use the Find and Replace feature, you can do this:

    First, search with this regex: (\d{2}:\d{2}:\d{2})$. The parenthesis create a group you can use for replacing.

    Then, replace with " $1", where the space adds your needed space and $1 matches the group we found.