-1

我有一个字符串

string1 = SIZE 15 by 1 ;

string2 = SIZE 3 by 56 ;

我正在 perl 和 awk 中逐行从文件中读取这些字符串,我想在一个变量中获取 15 和在一个变量中获取 1 的字符串中的数字,比如在一个变量中获取 3,在一个变量中获取 56。

我用 $frag1 = substr(line,9,2); $frag2 = substr(line,15,1); 在 awk 中,它适用于第一个字符串,但对于第二个字符串失败,因为第二个字符串中的第一个数字只有一个数字。

任何想法,任何我可以使用的正则表达式。谢谢

4

4 回答 4

2

如果你的文件有“string1 = SIZE 15 by 1;”形式的行,你可以使用命令awk '{print $4, $6}'。如果您的行是“SIZE 15 by 1”,您可以运行awk '{print $2, $4}'. 不需要正则表达式

于 2013-08-14T06:22:02.687 回答
0

If you're using Gawk you can take advantage of the extended match() function:

if (match($0, /string[0-9]+ = SIZE ([0-9]+) by ([0-9]+)/, a)) {
    print $0 " matches with values " a[1] " and " a[2] "."
}
于 2013-08-14T06:31:57.633 回答
0

正则表达式(\d+)应该可以解决问题。您可以将保存的变量与$1.

当你的字符串 $str 像你说的那样定义时

my $str = "string1 = SIZE 15 by 1 ;";

正则表达式可能看起来像

/string \d \s = \s SIZE \s (\d+) \s by \s (\d+) \s ;/x

其中变量151保存为$1$2

于 2013-08-14T06:22:33.140 回答
0
my ($first, $second) = $string1 =~ /\b(\d+)\b/g;

\b匹配word boundary字符串中的数字,如string11string不匹配。

于 2013-08-14T06:36:06.930 回答