PHP正则表达式失败
我当前的正则表达式应该是正确的,尽管我不希望如此,但它不能正常工作。它不会返回“已匹配” 我的货币代码如下:PHP正则表达式失败,php,regex,Php,Regex,我当前的正则表达式应该是正确的,尽管我不希望如此,但它不能正常工作。它不会返回“已匹配” 我的货币代码如下: $id = "http://steamcommunity.com/id/TestID"; if (preg_match("^http://steamcommunity\.com/id/.*?\n$", $id)) { print "Got match!\n"; } 您需要一个分隔符,如下所示: if (preg_match("#^http://steam
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("^http://steamcommunity\.com/id/.*?\n$", $id)) {
print "Got match!\n";
}
您需要一个分隔符,如下所示:
if (preg_match("#^http://steamcommunity\.com/id/.*?$#", $id)) {
^ ^
最后的新线是什么?当然你不需要了。你失踪了。例如:
"#^http://steamcommunity\.com/id/.*?\n$#"
此外,您正在尝试匹配不在字符串中的换行符(
\n
)。您需要添加模式分隔符:
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("#^http://steamcommunity\.com/id/.*?(\n|$)#", $id)) {
print "Got match!\n";
}
<?php
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("#^http://steamcommunity\.com/id/.*?$#", $id)) {
print "Got match!\n";
}
?>
您的正则表达式中缺少分隔符:
if (preg_match("#^http://steamcommunity\.com/id/.*?\n$#", $id)) {
^--here ^--here
请注意,我在这里使用了
#
作为分隔符,因为这样可以省去所有内部/
字符的转义,如果您使用传统的/
作为分隔符。您需要在模式中使用起始和结束分隔符,如/pattern/
或#pattern
或带括号的(模式)
。为什么呢?在结束分隔符后使用一些模式修饰符,如#pattern#i
(忽略大小写)
资源:
它有两个问题。首先,需要用一个字符分隔正则表达式的开始和结束。我用了
#
。您还在正则表达式的末尾匹配一个新行,这在您的字符串中没有,也可能永远不会有
<?php
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("#^http://steamcommunity\.com/id/.*?$#", $id)) {
print "Got match!\n";
}
?>
首先,您的正则表达式甚至不应该编译,因为它缺少分隔符
if (preg_match("~^http://steamcommunity\.com/id/.*?\n$~", $id)) {
^---- these guys here -----^
其次,如果字符串不包含新行,为什么要有一个\n
最后,你为什么要用正则表达式呢?实际上,您只是试图匹配一个常量字符串。这应等同于您试图匹配的内容:
if (strpos($id, 'http://steamcommunity.com/id/') === 0) {
正如人们所说,你的模式是开始和结束错误的。(分隔符)
但这将更好地匹配64位Steam ID(最少17个,最多25个) 我相信你没有必要要求绳子必须以断线结束 解释。
http://steamcommunity\.com/id/([0-9]{17,25})
^--- string ---^^-- Regexp --^
[0-9]-匹配0到9之间的数字{17,25}-进行17到25次匹配
()-返回匹配 或使用相同的模式(相同):
您忘记了转义url中的
/
,如果您使用/
作为分隔符,这是必需的。我十秒钟前编辑了这篇文章,以使用不同的分隔符。为什么有php问题的perl答案?+1。我知道这在perl中是可能的,并且经常使用它,但我不知道在php中也是可能的。但我几乎从未使用过php。关于这个问题,还有一个新行,他试图与之匹配。preg是“perl兼容”的,并且实现了几乎所有可以在perl正则表达式中实现的功能。是的,但我认为分隔符更多地是语言语法,而不是正则表达式的一部分。我发现不是这样,因为它通常是在结束分隔符后带有可选标志的正则表达式字符串的一部分
if( preg_match("#^http://steamcommunity\.com/id/([0-9]{17,25})#i", $id, $matches) )
{
echo "Got match! - ".$matches;
}
http://steamcommunity\.com/id/([0-9]{17,25})
^--- string ---^^-- Regexp --^
/^http:\/\/steamcommunity\.com\/id\/([0-9]{17,25})/i
(^http://steamcommunity\.com/id/([0-9]{17,25}))i