我想要做的是给出一个类似如下的字符串:
"hello GigabitEthernet1/13 mplampla"
要提取接口,例如:
"GigabitEthernet1/13"
要提取前2个字符,然后提取端口号,例如:
"Gi1/13"
我做错了什么?
#!/usr/bin/perl -w
use strict ;
use warnings ;
my $string = "hello GigabitEthernet1/13 mplampla" ;
$string =~ /(^[a-z]{2}*[0-9]\/*[0-9]*\/*[0-9]*)/ ;
print $string."\n" ;
PS。端口号可以类似于"Po4
“、"TenGigabitEthernet2/0/0.13
”等。
发布于 2012-01-31 06:47:18
一种方法:
use strict ;
use warnings ;
my $string = "hello GigabitEthernet1/13 mplampla" ;
my @result = $string =~ /\s(\w{2})(?:\D*)(\d+\S*)/;
{
local $" = qq[];
print qq[@result\n];
}
正则表达式:
\s # A space character.
(\w{2}) # Two alphabetic characters. Save as group 1.
(?:\D*) # Any no-numeric characters. No save them.
(\d+\S*) # From first digit found until a space. Save as group 2.
用于打印:
$" # It is the separator for array elements. It is set to a blank.
@result # It is an array with grouped elements of the regular expression.
发布于 2012-01-31 06:47:34
您的正则表达式有几个问题--让我们逐个解决它们。
^
字符时,表示“行的开始”。因此,您已经告诉正则表达式引擎,您要查找的内容位于输入字符串的最开始,但这不是真的。所以去掉^
,,
[a-z]
,你已经明确告诉引擎只查找小写字母。您可以将其更改为[A-Za-z]
,也可以在最后一个斜杠后面添加一个i
,以使您拥有的正则表达式case-insensitive.*
的位置没有意义--我认为您的本意是将如下内容放在其位置:[a-z]*
(表示0个或更多个字母)。所以应用所有这些更改,下面是您的新正则表达式:
/([a-z]{2}[a-z]*[0-9]\/*[0-9]*\/*[0-9]*)/i
该正则表达式将捕获GigabitEthernet1/13
。
编辑:这里是一个你可以尝试你的正则表达式的地方,看看它是如何响应变化的:
http://rubular.com/r/lsucbd8E4J
发布于 2012-01-31 07:12:00
使用捕获组:
$string =~ s|
^.* # match beginning text (to be replaced)
\b(\w{2})\w+ # capture the first two letters (in $1)
(
(?: \d+/? )+ # and one or more digits followed by 0 or 1 slashes,
# one or more times (in $2)
)
.*$ # match ending text (to be replaced)
|$1$2|x; # replace with only the contents of the capture groups
https://stackoverflow.com/questions/9071839
复制相似问题