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

后端 未结 3 1387
故里飘歌
故里飘歌 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:13

    Use the \b anchor to match only on a word boundary:

    s/\bcat\b/cat_tastic/g
    

    Although Perl has a slightly different definition of what a "word" is. Reading the perlre reference guide a couple of times might help you understand regexps a bit better.

    Running perl -pi -e "YOUR_REGEXP" in a terminal and entering in lines of text can help you understand and debug what a particular regexp is doing.

    0 讨论(0)
  • 2020-12-07 06:24

    See the example on this page which explains boundary matchers

    Enter your regex: \bdog\b
    Enter input string to search: The dog plays in the yard.
    I found the text "dog" starting at index 4 and ending at index 7.
    
    Enter your regex: \bdog\b
    Enter input string to search: The doggie plays in the yard.
    No match found.
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题