Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While replacing using regex, How to keep a part of matched string?

I have

12.hello.mp3 21.true.mp3 35.good.mp3 . . . 

so on as file names in listed in a text file.

I need to replace only those dots(.) infront of numbers with a space.(e.g. 12.hello.mp3 => 12 hello.mp3). If I have regex as "[0-9].", it replaces number also. Please help me.

like image 409
Srikanth P Vasist Avatar asked Jan 22 '13 12:01

Srikanth P Vasist


People also ask

How do you replace a section of a string in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

How do I replace only part of a match with Python re sub?

Put a capture group around the part that you want to preserve, and then include a reference to that capture group within your replacement text. @Amber: I infer from your answer that unlike str. replace(), we can't use variables a) in raw strings; or b) as an argument to re. sub; or c) both.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.


2 Answers

Replace

^(\d+)\.(.*mp3)$ 

with

\1 \2 

Also, in recent versions of notepad++, it will also accept the following, which is also accepted by other IDEs/editors (eg. JetBrains products like Intellij IDEA):

$1 $2 

This assumes that the notepad++ regex matching engine supports groups. What the regex basically means is: match the digits in front of the first dot as group 1 and everything after it as group 2 (but only if it ends with mp3)

like image 98
Ioan Alexandru Cucu Avatar answered Sep 25 '22 06:09

Ioan Alexandru Cucu


I tested with vscode. You must use groups with parentheses (group of regex)

Practical example

  • start with sample data
1 a text 2 another text 3 yet more text 
  • Do the Regex to find/Search the numerical digits and spaces. The group here will be the digits as it is surrounded in parenthesis
(\d)\s 
  • Run a replace regex ops. Replace spaces for a dash but keep the numbers or digits in each line
$1- 
  • Outputs
1-a text 2-another text 3-yet more text 
like image 37
Andre Leon Rangel Avatar answered Sep 22 '22 06:09

Andre Leon Rangel