Regex to match whole word with a particular definition of a word

后端 未结 3 1388
故里飘歌
故里飘歌 2020-12-07 05:40

I am doing a file search and replace for occurrences of specific words in perl. I\'m not usually much of a perl or regex user. I have searched for other regex questions here

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 06:25

    You could try:

    s/([^0-9a-z_])([0-9a-z_]+)([^0-9a-z_])/$1$2_tastic$3/gi
    

    Basically, a non-word character, then a set of word characters, followed by a non-word character. The $1,$2,$3 represent the captured groups, and you replace $2 with $2_suffix.

    Hope that helps, not a perl guy buy pretty regex-savvy. Note that the above will fail if the word is the very first or very last thing in a string. Not sure if perl regexen allow the syntax, but if so, fixing the first/last issue could be done with:

    s/(^|[^0-9a-z_])([0-9a-z_]+)([^0-9a-z_]|$)/$1$2_tastic$3/gi
    

    Using ^ and $ to match beginning/end of string.

提交回复
热议问题