我是工作和正则表达的新手。我正在使用php。
对于以下字符串,我想提取报告编号。
Dear Patient! (patient name) Your Reports(report number) has arrived.
有人可以帮助我创建正则表达式。
谢谢
解决了:
$str ='Dear Patient! (P.JOHN) Your Reports (REPORTNO9) has arrived.';
$str = str_replace('(', '', $str);
$str = str_replace(')', '', $str);
preg_match('/Reports\s*(\w+)/', $str, $match);
echo $match[1]; //=> "REPORTNO9"
答案 0 :(得分:1)
正则表达式
/Dear (\w+)! Your Reports(.*?)(?=has arrived)/
PHP使用
<?php
$subject = 'Dear Patient! Your Reports(report number) has arrived.';
if (preg_match('/Dear (\w+)! Your Reports(.*?)(?=has arrived)/', $subject, $regs)) {
var_dump($regs);
}
<强>结果强>
array(3) {
[0]=>
string(42) "Dear Patient! Your Reports(report number) "
[1]=>
string(7) "Patient"
[2]=>
string(16) "(report number) "
}
<强>解释强>
"
Dear\ # Match the characters “Dear ” literally
( # Match the regular expression below and capture its match into backreference number 1
\w # Match a single character that is a “word character” (letters, digits, etc.)
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
!\ Your\ Reports # Match the characters “! Your Reports” literally
( # Match the regular expression below and capture its match into backreference number 2
. # Match any single character that is not a line break character
*? # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
)
(?= # Assert that the regex below can be matched, starting at this position (positive lookahead)
has\ arrived # Match the characters “has arrived” literally
)
"
答案 1 :(得分:0)
您可以使用&#34; split()&#34;提取这样的字符串的特定部分,所以你不必使用正则表达式:
<?php
$my_string = ""; // Put there you string
$array_my_string = array();
$array_my_string = split('Reports', $my_string);
$tempResult = array_my_string[1]; // Will contains "(report number) has arrived."
$array_my_string = split(' has arrived', $tempResult);
$finalResult = $array_my_result[0]; // Will contains "(report number)"
?>