The following is a sample string I will be searching which will be on a separate line with other strings:
Chapter 1: My name is: Shojib (aka mhs)
Here is my regular expression to find that particular line: (Chapter)( )([0-9])(:)( .*)
Now I want to keep the words and integers, and remove the punctuation, and separate each words and integers with an underscore. For example, this is how the format should look after replacing:
Chapter_1_My_name_is_Shojib_aka_mhs
Because you didn’t mention the language, this answer is using Perl notation. The exact replace syntax depends on your used language.
You need to do it with two regexes. The first one that removes the punctuation and the second one to replace the whitespace with underscores.
Means match
[^\w\s]and replace it with ”.\wa word character (contains different characters depending on your regex engine at least 0-9a-zA-Z_ if your language supports Unicode it can be that all letters are in\w)\sa whitespace character[]a character class^at the first position inside a character class is the negation[^\w\s]all characters that are not \w and \sThis will replace anything that is not a word character and not a whitespace with nothing.
The second step is to replace the remaining whitespace with _
Your regex
(Chapter)( )([0-9])(:)( .*)to find your row can also be improved. If you use brackets, you create capturing groups, that means the matched pattern is stored into a variable. So it makes no sense to search forChapterand store this into a variable, its already known. if you don’t need those variables you can reduce your regex to:\dis the same than[0-9]\s*means any amount of whitespaceDo you expect chapter numbers bigger than 9? Then use
+means at least one, so\d+will match on at least one digit.