我是regexp的初学者,我需要匹配以下内容:
Tab[0]hash/0-786541/value : 12
我尝试过很多东西,但是不相符。
例如 :
^([\w\[\*\]]*[\w\/(0-9)\-(0-9){8})\/]\w)\s*:\s*
谢谢您的帮助
你可以使用下面的代码。
#!/usr/bin/perl
$str="Tab[0]hash/0-786541/value : 12";
if ($str =~ /(\w)*\[(\d)\](\w)*\/(\d)-([0-8])*\/(\w)*(\s)\:(\d)*/)
{
print "matched\n";
}
else
{
print "not matched\n";
}
(\w)*: [a-zA-Z] followed by zero\more times of [a-zA-Z]
\[ : \[ escape [ so that perl interpreter not to think it as start of charecter class
(\d) : followed bu any digit
\] : \] escape ] so that perl interpreter not to think it as end of charecter class
(\w)*: [a-zA-Z] followed by zero\more times of [a-zA-Z]
\/ : escape / so that perl interpreter not to think it as end on regular expression
(\d) : followed by a digit [0-9]
- : followed by -
([0-8])*: followed by [0-8] (zero\more times)
\/ : escape / so that perl interpreter not to think it as end on regular expression
(\w)*: [a-zA-Z] followed by zero\more times of [a-zA-Z]
(\s) : followed by a space
\: : followed by a colon
(\d)*: followed by digits [0-9] (zero\more times)
假设字符串需要由/
和:
解析,这里有一些解析的基本方法
my $str = 'Tab[0]hash/0-786541/value : 12';
使用split
my @parts = split /\/|:/, $str;
字符串在/
或:
上拆分,因为split
在/.../
中为其模式规范采用完整的正则表达式。我们还可以在匹配时清理大部分空间
my @parts = split /\s*(?:\/|:)\s*/, $str;
什么返回列表中的元素没有周围的空格(除了尾随空格,在字符串的末尾)。使用non-capturing group (?:...)
与()
一起捕获并返回分隔符。
使用正则表达式
my @parts = $str =~ m{ \s* ([^/:]+) \s* }gx;
匹配任何不是/
或:
的东西,一次或多次。 /g
修饰符使其继续直到字符串耗尽,匹配模式的所有匹配并返回()
捕获的匹配列表。
我使用{}
分隔符不必逃避/
,然后需要m{}
。使用/x
修饰符,我们可以自由地使用空格,换行符和注释(它们不匹配),以提高可读性。
然后我们可以分开数字
my @num = pop @parts;
在这两种情况下。
这可以通过更具体的模式进行解析,但为此我们确实应该知道需要提取什么。人们通常在字符串中使用“地标”模式,以便能够形成精确的匹配目标,并且能够从中获得所需内容,而不是指定每个元素。
如果显示的字符串表示文件中的典型行
use warnings;
use strict;
my $file = '...';
open my $fh, '<', $file or die "Can't open $file: $!";
while (<$fh>)
{
my @parts = m{\s*([^/:]+)\s*}g; #/
my $num = pop @parts;
print "@parts -- $num\n";
# Reassemble (up to extra spaces), perhaps for a check
# my $orig_str = join('/', @parts) . " : $num";
}
(那个#/
只是通过标记来关闭错误的语法高亮)
my $str = 'Tab[0]hash/0-786541/value : 12';
if($str=~m{^(\w)*\[.*?\]([^\/]*)/([^\/]*)/([^\:]*)\s*\:\s*([^\d\w]*)\n?})
{
print "Matches...\n"
}
试试这个: