如何在正则表达式中转义以前未知的字符串

如何在正则表达式中转义以前未知的字符串

本文介绍了如何在正则表达式中转义以前未知的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要 egrep 一个在运行前未知的字符串,我将通过 shell 变量获得它(shell 是 bash,如果这很重要).问题是,该字符串将包含特殊字符,如大括号、空格、点、斜线等.

I need to egrep a string that isn't known before runtime and that I'll get via shell variable (shell is bash, if that matters). Problem is, that string will contain special characters like braces, spaces, dots, slashes, and so on.

如果我知道字符串,我可以一次对一个特殊字符进行转义,但如何对整个字符串进行转义?

If I know the string I can escape the special characters one at a time, but how can I do that for the whole string?

通过 sed 脚本运行字符串以在每个特殊字符前加上 可能是一个想法,我仍然需要 rtfm 应该如何编写这样的脚本.我不知道是否还有其他更好的选择.

Running the string through a sed script to prefix each special character with could be an idea, I still need to rtfm how such a script should be written. I don't know if there are other, better, options.

我确实读过 re_format(7) 但似乎没有像将整个下一个字符串作为文字"这样的东西......

I did read re_format(7) but it seems there is no such thing like "take the whole next string as literal"...

为了避免误报,我还应该在模式中添加换行检测,例如.egrep '^myunknownstring'

to avoid false positives, I should also add newline detection to the pattern, eg. egrep '^myunknownstring'

推荐答案

如果您需要将字符串嵌入到更大的表达式中,sed 就是我的方法.

If you need to embed the string into a larger expression, sed is how I would do it.

s_esc="$(echo "$s" | sed 's/[^-A-Za-z0-9_]/\&/g')" # backslash special characters
inv_ent="$(egrep "^item [0-9]+ desc $s_esc loc .+$" inventory_list)"

这篇关于如何在正则表达式中转义以前未知的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:07