正则表达式将整个单词与单词的特定定义匹配 [英] Regex to match whole word with a particular definition of a word

查看:48
本文介绍了正则表达式将整个单词与单词的特定定义匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行文件搜索并替换 perl 中出现的特定单词.我通常不是一个 perl 或 regex 用户.我在这里搜索了其他正则表达式问题,但找不到一个非常正确的问题,所以我在寻求帮助.我的搜索和替换目前看起来像这样:

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 but I couldn't find one which was quite right so I'm asking for help. My search and replace currently looks like this:

s/originalword/originalword_suffix/g

这匹配出现在另一个单词中间的 originalword 的情况,这是我不想要的.在我的搜索和替换应用中,可以将整个单词定义为具有小写或大写拉丁字母表中的字母以及任何不间断序列中的数字 0-9 和符号 _.除了这些字符之外的任何其他字符,包括任何其他符号或任何形式的空格,包括换行符或制表符,都表示某种操作或分隔符,因此它们在单词边界之外.如何修改我的搜索和替换以仅匹配我定义的整个单词,而不匹配子字符串?

This matches cases of originalword that appear in the middle of another word, which I don't want. In my application of search and replace, a whole word can be defined as having the letters of the latin alphabet in lowercase or capital letters and the digits 0-9 and the symbol _ in any uninterrupted sequence. Anything else besides these characters, including any other symbols or any form of whitespace including line breaks or tabs, indicate operations or separators of some kind so they are outside the word boundaries. How do I modify my search and replace to only match whole words as I've defined them, without matching substrings?

示例:

在 originalword = cat 和 originalword_suffix = cat_tastic 的情况下

in the case that originalword = cat and originalword_suffix = cat_tastic

:cat { --> :cat_tastic {
:catalog { --> no change

推荐答案

使用 \b 锚点仅匹配单词边界:

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

s/\bcat\b/cat_tastic/g

尽管 Perl 对词"的定义略有不同.多读几次 perlre 参考指南可能会帮助您更好地理解正则表达式.

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.

在终端中运行 perl -pi -e "YOUR_REGEXP" 并输入文本行可以帮助您理解和调试特定正则表达式正在做什么.

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.

这篇关于正则表达式将整个单词与单词的特定定义匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆