本文概述
- Perl匹配运算符
- 匹配运算符修饰符
- Perl匹配运算符=?
- Perl匹配运算符!?
- $ _的Perl匹配运算符
- Perl匹配运算符与m
- Perl匹配运算符, 含$ 1, $ 2 …
- Perl匹配运算符?
- Perl替代运算符
- 带s ///的Perl替代运算符
- Perl翻译运算符
- Perl翻译运算符替换一个字母
- Perl Translation Operator替换多个字母
perl中包含三个正则表达式运算符:
- 匹配正则表达式运算符
- 替代正则表达式运算符
- 音译正则表达式运算符
匹配运算符修饰符
Operators | Description |
---|---|
cg | 即使全局匹配失败也继续搜索 |
g | 全局搜索所有匹配项 |
i | 搜索不区分大小写的匹配项 |
m | 如果字符串具有换行符, 则$和^将与换行符而不是字符串边界匹配 |
o | 只允许一次表达式评估 |
s | 采用 。匹配换行符 |
x | 在表达式中使用空格 |
$line = "This is srcmini.";
if ($line =~ /java/){
print "Matching\n";
}else{
print "Not Matching\n";
}
if ($line =~ /Java/){
print "Matching\n";
}else{
print "Not Matching\n";
}
输出
Matching
Not Matching
Perl匹配运算符!?它与较早版本(=?)相反。如果字母匹配, 则输出不匹配, 反之亦然。
$ line = "This is srcmini.";
if ($line!~ /java/){
print "Matching\n";
}else{
print "Not Matching\n";
}
if ($line!~ /Java/){
print "Matching\n";
}else{
print "Not Matching\n";
}
输出
Not Matching
Matching
$ _的Perl匹配运算符你还可以将其与特殊的默认变量$ _匹配。
$_ = "This is srcmini.";
if (/java/) {
print "Matching\n";
}
else {
print "Not Matching\n";
}
if (/Java/) {
print "Matching\n";
}
else {
print "Not Matching\n";
}
输出
Matching
Not Matching
Perl匹配运算符与m匹配运算符m还用于匹配给定字符串中的单词。
$ line = "This is srcmini.";
if ($line=~ m[java]){
print "Matching\n";
}else{
print "Not Matching\n";
}
if ($line=~ m{Java}){
print "Matching\n";
}else{
print "Not Matching\n";
}
输出
Matching
Not Matching
Perl匹配运算符, 含$ 1, $ 2 … $ 1, $ 2将根据指定的括号打印单词。
my $word = "CuNaHg";
$word =~ /(((Cu)(Na))(Hg))/;
print "1: $1 2: $2 3: $3 4: $4 5: $5 6: $6\n";
输出
1: CuNaHg 2: CuNa 3: Cu 4: Na 5: Hg 6:
Perl匹配运算符?它从给定的字符串在括号内打印匹配的字符。
my $word = "CuNaHg";
$word =~ /(?:(Cu)NaHg)/;
print "$1\n";
# prints "Cu"
$word =~ /(?:Cu(Na)Hg)/;
print "$1\n";
# prints "Na"
$word =~ /(?:CuNa(Hg))/;
print "$1\n";
# prints "Hg?
【Perl正则表达式】输出
Cu
Na
Hg
Perl替代运算符替换运算符只是匹配运算符的扩展。它允许替换与某些新文本匹配的文本。
其基本语法为:
s/oldPattern/newPattern /;
带s ///的Perl替代运算符在这里, 我们在第一部分中用s ///将液体替换为固体。
在第二部分中, 以s /// g整体将” 液体” 替换为” 固体” 。
$line = "liquid will remain liquid until it is evaporated";
$line =~ s/liquid/solid/;
print "$line\n";
print"\n";
$line = "liquid will remain liquid until it is solidified";
$line =~ s/liquid/solid/g;
print "$line\n";
输出
solid will remain liquid until it is evaporated
solid will remain solid until it is evaporated
Perl翻译运算符翻译运算符与替换运算符相似。但是转换不使用正则表达式来搜索替换值。
其基本语法为:
tr/oldLetter/newLetter /;
Perl翻译运算符替换一个字母在此, 翻译运算符会将所有” l” 字母替换为” z” 字母。
$line = "liquid will remain liquid until it is evaporated";
$line =~ tr/l/z/;
print "$line\n";
输出
ziquid wizz remain ziquid untiz it is evaporated
Perl Translation Operator替换多个字母在这里, 翻译运算符会将所有的” l” 和” i” 字母替换为” z” 和” x” 字母。
$line = "liquid will remain liquid until it is evaporated";
$line =~ tr/li/zx/;
print "$line\n";
输出
zxquxd wxzz remaxn zxquxd untxz xt xs evaporated
推荐阅读
- Perl标量用法
- Perl redo语句
- Perl print()和say()
- Perl运算符
- Perl运算符类型
- Perl对象概念(面向对象编程)
- Perl next语句
- Perl多维数组
- Perl模块和命名空间