匹配单个数字以外的所有内容的正则表达式是什么?例如,stack应该匹配,stack overflow也应该匹配,12389237应该匹配,但2不应该匹配。我使用了^[^\d]+$,但显然它不能满足我的第三个条件。
编辑:顺便说一下,这是为PHP准备的。
编辑:顺便说一下,这是为PHP准备的。
将其分解为两种情况。要么匹配一个不是数字的单个字符,要么匹配长度大于等于2的任意字符串:
^(\D|.{2,})$
! /(?<!\d)\d(?!\d)/
/^(?!.*(?<!\d)\d(?!\d))/
或通过/x
进行传播:
/ ^ (?! .* (?<! \d) \d (?! \d) )/x
或者在各种多行情况下进行隔离:
/ \A (?! .* (?<! \d) \d (?! \d) )/sx
看到我为什么说否定一个正则表达式匹配更容易了吗?
这是测试程序:
use v5.12;
while (<DATA>) {
my $got = / ^ (?! .* (?<! \d) \d (?! \d) )/x;
print $got ? "PASS" : "FAIL";
print ": ", $_;
}
__END__
"stack" should match
"stack overflow" should match
"12389237" should match but
"2" should not match
这将会产生:
PASS: "stack" should match
PASS: "stack overflow" should match
PASS: "12389237" should match but
FAIL: "2" should not match
如果你的问题格式不正确,而且你只是想说这些字符串实际上是
stack
stack overflow
12389237
2
如果要实现这个功能,简单的方法是对单个数字进行否定匹配:
! /^\d$/
! /\A\d\z/
/^ (?! \d $ )/x
这是另一个测试程序:
use v5.12;
while (<DATA>) {
my $got = /^ (?! \d $ )/x;
print $got ? "PASS" : "FAIL";
print ": $_";
}
__END__
stack
stack overflow
12389237
2
报告显示:
PASS: stack
PASS: stack overflow
PASS: 12389237
FAIL: 2
use re "/msx"
语法规则,也必须保证正确的行为。 - tchrist不匹配单个数字,反向匹配:
!/^\d\z/
或者使用负向先行断言进行正则表达式匹配:
/^(?!\d\z)/
\Z
或$
。否则,+1,因为这正是我要发布的内容。 - TLP"2\n"
),你可以使用 $
或 \Z
而不是 \z
。 - Qtax一定要用正则表达式吗?对于 PHP,你可以这样做
is_integer($string) && $string < 10
Undefined subroutine &main::is_integer called at..
- TLP\D
放在周围的方括号中。 - tchrist/g
或 /m
有什么意义。你在想什么? - tchristwhile(my $line = <DATA>){
chomp $line;
if ($line !~ /^\d{1}$/) {
print "$line match\n";
}
else {
print "$line NOT match\n";
}
}
__DATA__
stack
stack overflow
12389237
2
结果:
perl regex.pl
stack match
stack overflow match
12389237 match
2 NOT match