正则表达式:如何捕捉一行的开头、一个模式和结尾


Regular expression: how to capture the beginning, a pattern and the end of a line?

以下是一些示例:

  1. Some text A
  2. Some text A 8:00-19:00
  3. 8:00-19:00
  4. Some text A 8:00-19:00 Some text B

对于上面描述的每种情况,我需要捕获(如果可能的话):

  • 时间(8:00-19:00
  • 开头(Some text A
  • 结束(Some text B

使用此模式#^(.*?) ?('d{1,2}:'d{2}-'d{1,2}:'d{2})?$#,我可以捕获(来自示例2):

  • Some text A
  • 8:00-19:00

但我无法通过在模式末尾添加(.*)(.*?)来捕捉行的其余部分。

你能帮我吗?非常感谢。

使用preg_split怎么样?

$tests = array(
    'Some text A',
    'Some text A 8:00-19:00',
    '8:00-19:00',
    'Some text A 8:00-19:00 Some text B'
);
foreach ($tests as $test) {
    $res = preg_split('/('d'd?:'d'd-'d'd?:'d'd)/', $test, -1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    print_r($res);
}

输出:

Array
(
    [0] => Some text A
)
Array
(
    [0] => Some text A 
    [1] => 8:00-19:00
)
Array
(
    [0] => 8:00-19:00
)
Array
(
    [0] => Some text A 
    [1] => 8:00-19:00
    [2] =>  Some text B
)
<?php
    $pattern = <<<REGEX
/
(?:
    (.*)?'s*                    #Prefix with trailing spaces
    (
        (?:'d{1,2}:'d{1,2}-?)   #(dd:dd)-?
        {2}                     #2 of those
    )                           #(The time)
    's*(.*)                     #Trailing spaces and suffix
    |
    ([a-zA-Z ]+)                #Either that, or just text with spaces
)
/x
REGEX;
    preg_match($pattern, "Some text A 8:00-19:00 Some text B", $matches);
    print_r($matches);

数组$matches将包含您需要的所有部分。

编辑:现在只匹配文本。

我认为您的主要问题是,通过在数字组后面添加?,使其成为可选数字组(我认为您不想要)。

这适用于我/^(.*) ?('d{1,2}:'d{2}-'d{1,2}:'d{2}) ?(.*)$/:

<?
$str = "Some text A 8:00-19:00 Some text B";
$pat = "/^(.*) ?('d{1,2}:'d{2}-'d{1,2}:'d{2}) ?(.*)$/";
if(preg_match($pat, $str, $matches)){
   /*
    Cases 2, 3 and 4
    Array
    (
        [0] => Some text A 8:00-19:00 Some text B
        [1] => Some text A 
        [2] => 8:00-19:00
        [3] => Some text B
    )
   */
}else{
   /* Case 1 */
}
?>

好。。。我不清楚具体情况是什么。

我相信你想匹配3个可选组(这可能会匹配"格式错误"的输入,除非你提供了你不想匹配的案例场景)。

这适用于所有示例,尽管在情况1中,"Some text A"出现在$matches[0]和$matches[3]中,而不是$matches[1]中。

/^([A-Za-z ]*?)([0-2]{0,1}[0-9]':[0-6][0-9]'-[0-2]{0,1}[0-9]':[0-6][0-9])?([A-Za-z ]*?)$/
相关文章: