正则表达式将整个单词与单词的特定定义匹配

编程入门 行业动态 更新时间:2024-10-11 13:26:46
本文介绍了正则表达式将整个单词与单词的特定定义匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在执行文件搜索并替换 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.

更多推荐

正则表达式将整个单词与单词的特定定义匹配

本文发布于:2023-11-02 12:09:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552361.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单词   定义   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!