如何仅使用正则表达式

时间:2017-12-04 18:41:29

标签: php regex

使用正则表达式从此URL中提取u2参数的值。 http://www.example.com?u1=US&u2=HA853&u3=HPA

<?php
$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA"; //my url
$pattern='/u2=[0-9A-Za-z]*/'; //R.E that url value is only digit/Alphabet 
preg_match($pattern,$subject,$match);
print_r($match[0]);
?>

输出: - U2 = HA853

我如何只检索HA853?

2 个答案:

答案 0 :(得分:1)

0组是正则表达式匹配的所有内容,因此要么使用\K来忽略正则表达式的先前匹配,

$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA"; //my url
$pattern='/u2=\K[0-9A-Za-z]*/'; //R.E that url value is only digit/Alphabet 
preg_match($pattern,$subject,$match);
print_r($match[0]);

或使用第二个捕获组:

...
$pattern='/u2=([0-9A-Za-z]*)/'; //R.E that url value is only digit/Alphabet 
...
print_r($match[1]);

为什么你需要这样做虽然我不清楚,http://php.net/manual/en/function.parse-str.php,似乎是一种更简单的方法。

$subject="http://www.example.com?u1=US&u2=HA853&u3=HPA";
parse_str($subject, $output);
echo $output['u2'];

演示:https://3v4l.org/gR4cb

答案 1 :(得分:1)

其他方式是使用parse_url,http://php.net/manual/en/function.parse-url.php

df.loc[df['Date'] == 'Nov 20, 2017', 'Close']