bash 在sed中,如何表示“字母数字或_或-”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23120346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:14:17  来源:igfitidea点击:

In sed, how to represent "alphanumeric or _ or -"

regexlinuxbashshellsed

提问by Alfred Zhong

Tried

试过

[a-zA-Z0-9-_]
[a-zA-Z0-0\-\_]
[[[:alnum:]]-_]
...

What is the correct way to represent that in regular expression?

在正则表达式中表示它的正确方法是什么?

It seems like [a-zA-Z0-9-] works for alphanumeric or dash. But when I add another underscore, it breaks.

似乎 [a-zA-Z0-9-] 适用于字母数字或破折号。但是当我添加另一个下划线时,它会中断。

回答by anubhava

That will be this character class:

那将是这个字符类:

[[:alnum:]_-]

Which means allow one of these:

这意味着允许以下之一:

1. Alpha numeric
1. Underscore
1. Hyphen

It is important to keep hyphen at 1st or last position in character class to avoid escaping.

将连字符保持在字符类中的第一个或最后一个位置以避免转义很重要。

回答by lurker

All of these variations will work:

所有这些变化都将起作用:

[a-zA-Z0-9_\-]
[a-zA-Z0-9_-]
[-_a-zA-Z0-9]
[-a-z_A-Z0-9]
[-a-zA-Z_0-9]
[-a-zA-Z0-9_]
...

The hyphen needs to be on one end. It can be escaped or not if at the end, and must be un-escaped if at the beginning. The underscore can be almost anywhere, as long as it's not in the middle of one of your ranges, and doesn't need to be escaped.

连字符必须在一端。结尾可以转义也可以不转义,开头必须不转义。下划线几乎可以在任何地方,只要它不在您的范围之一的中间,并且不需要转义。