douhu4091 2012-09-30 13:53
浏览 239
已采纳

使用正则表达式匹配多个变量(PHP / JS)

I understand how to use PHP's preg_match() to extract a variable sequence from a string. However, i'm not sure what to do if there are 2 variables that I need to match.

Here's the code i'm interested in:

$string1 = "help-xyz123@mysite.com";
$pattern1 = '/help-(.*)@mysite.com/'; 
preg_match($pattern1, $string1, $matches);
print_r($matches[1]); // prints "xyz123"

$string2 = "business-321zyx@mysite.com";

So basically I'm wondering how to extract two patterns: 1) Whether the string's first part is "help" or "business" and 2) whether the second part is "xyz123" vs. "zyx321".

The optional bonus question is what would the answer look like written in JS? I've never really figured out if regex (i.e., the code including the slashes, /..../) are always the same or not in PHP vs. JS (or any language for that matter).

  • 写回答

2条回答 默认 最新

  • doujiufutaog59220 2012-09-30 14:03
    关注

    The solution is pretty simple actually. For each pattern you want to match, place that pattern between parentheses (...). So to extract any pattern use what've you already used (.*). To simply distinguish "help" vs. "business", you can use | in your regex pattern:

    /(help|business)-(.*)@mysite.com/
    

    The above regex should match both formats. (help|business) basically says, either match help or business.

    So the final answer is this:

    $string1 = "help-xyz123@mysite.com";
    $pattern1 = '/(help|business)-(.*)@mysite.com/'; 
    preg_match($pattern1, $string1, $matches);
    print_r($matches[1]); // prints "help"
    echo '<br>';
    print_r($matches[2]);  // prints "xyz123"
    

    The same regex pattern should be usable in Javascript. You don't need to tweak it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败