珀尔 |正则表达式字符类
字符类用于字符字符串。这些类让用户匹配任何用户事先不知道的字符范围。要匹配的字符集总是写在方括号 []之间。一个字符类总是与一个字符完全匹配。如果未找到匹配,则整个正则表达式匹配失败。
例子:
Suppose you have a lot of strings like #g#, #e#, #k#, #k#, #s#, #.# or #@# and you have to match a # character which is followed by ‘g‘, ‘e‘, ‘k‘, ‘s‘, ‘.‘, or ‘@‘, followed by the another # character, then try the regex /[#geeks@.#]/ that will match the required. It will start a match with # and then match any character in [] and after that match another #. This regex will not match “##” or “#ge#” or “#gg#” etc. because as said earlier that the character class always match exactly one character between the two ‘#‘ characters.
要点:
- 字符类中的 Dot(.) 失去了它的特殊含义,即“除换行符之外的所有内容”。
- Dot(.) 只能匹配字符类中的单个点(.)。
- 大多数特殊字符在字符类中失去了它们的特殊含义,但有些字符在字符类中获得了一些特殊含义。
例子:
# Perl program to demonstrate
# character class
# Actual String
$str = "#g#";
# Prints match found if
# its found in $str
if ($str =~ /[#geeks@.#]/)
{
print "Match Found\n";
}
# Prints match not found
# if it is not found in $str
else
{
print "Match Not Found\n";
}
输出:
Match Found
字符类中的范围:要匹配一长串字符非常难以键入,因为用户可能会跳过一个或两个字符。因此,为了使任务简单,我们将使用范围。通常,破折号(-) 用于指定范围。
例子:
To specify range [abcdef] you can use /[a-f]/
要点:
- 范围使用-(Dash) 符号指定。
- 用户还可以组合多个范围的字符、数字等,例如 [0-9a-gA-g]。这里' - '允许用户取范围内指定的任意数量的字符或数字
- 如果用户想要匹配给定字符串中的破折号(-),那么他可以简单地将其放在方括号 []之间。
- 要匹配字符串中的右方括号,只需在其前面加上\即\]并将其放在方括号 []之间。
例子:
# Perl program to demonstrate
# range in character class
# Actual String
$str = "61geeks";
# Prints match found if
# its found in $str
# using range
if ($str =~ /[0-7a-z]/)
{
print "Match Found\n";
}
# Prints match not found
# if its not found in $str
else
{
print "Match Not Found\n";
}
输出:
Match Found
否定字符类:要否定字符类,只需使用插入符号(^)符号。它将否定符号甚至范围之后的指定字符。如果您将插入符号 (^) 作为字符类中的第一个字符,则意味着字符类可以匹配除字符类中提到的字符之外的任何一个字符。
例子:
# Perl program to demonstrate
# negated character class
# Actual String
$str = "geeks56";
# using negated character class
# Prints match found if
# its found in $str
if ($str =~ /[^geeks0-7]/)
{
print "Match Found\n";
}
# Prints match not found
# if its not found in $str
else
{
print "Match Not Found\n";
}
输出:
Match Not Found