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 w开发者_运维问答ith 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.
s/[^\w\s]//g
Means match [^\w\s]
and replace it with ''. \w
a 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
)
\s
a 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 \s
This 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 _
s/\s/_/g
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 for Chapter
and store this into a variable, its already known. if you don't need those variables you can reduce your regex to:
Chapter\s*\d:.*
\d
is the same than [0-9]
\s*
means any amount of whitespace
Do you expect chapter numbers bigger than 9? Then use
Chapter\s*\d+:.*
+
means at least one, so \d+
will match on at least one digit.
The requirement is not terribly clear, but this should do it...
/[^A-Za-z0-9]/_/g
Put any character you do not want to replace with an underscore in the brackets
精彩评论