【问题标题】:Return NonMatching Part of Regex返回正则表达式的不匹配部分
【发布时间】:2016-09-26 14:49:54
【问题描述】:

我目前正在尝试格式化 Brandname 的某些部分,但我无法获取需要格式化的部分,例如:

BrandTest®
BrandBottle®
BrandJuice®

我想要Brand® 之间的部分。

我目前尝试过类似:/(?=(Brand))+(.*)+(®)/

但是除了中间的部分,我什么都得到了。

【问题讨论】:

  • 您不太了解什么是前瞻。

标签: php regex


【解决方案1】:

你可以改变你的正则表达式来使用它:

Brand(.*?)®

Working demo

php代码

$re = "/Brand(.*?)®/"; 
$str = "BrandTest® BrandBottle® BrandJuice®"; 

preg_match_all($re, $str, $matches);

【讨论】:

    【解决方案2】:

    可能是这样的:

    <?php
    $brands = 'BrandTest® BrandBottle® BrandJuice®';
    $brands = explode('Brand', $brands);
    //you will get each brand in an array as:
    //"Test®", "Bottle®", "Juice®"
    ?>
    

    如果您不想要®,那么这可能会帮助https://stackoverflow.com/a/9826656/4977144

    【讨论】:

      【解决方案3】:

      将其汇总到一个方法中并返回您的结果:

      function getQueryPiece($queryString) {
          preg_match('/\?\=Brand(.*)®/',$queryString,$matches);
          return $matches[1];
      }
      
      getQueryPiece("?=BrandBottle®"); // string(6) Bottle  
      getQueryPiece("?=BrandTest®"); // string(4) Test  
      getQueryPiece("?=BrandJuice®"); // string(5) Juice  
      

      这仅定义了 1 个捕获组(?=Brand® 之间的字符串片段)。如果您还需要捕获其他部分,只需将每个部分包裹在括号中:'/(\?\=Brand)(.*)(®)/' 但是这将改变该部分在$matches 数组中的位置。它将是位置 2。

      我相信您的模式中最初的问题是使用“?”的结果未转义。问号在正则表达式中有特殊含义。这是一篇很好的文章:Regex question mark

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-12
        • 1970-01-01
        相关资源
        最近更新 更多