简体   繁体   English

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

[英]Matching multiple variables using regex (PHP/JS)

I understand how to use PHP's preg_match() to extract a variable sequence from a string. 我理解如何使用PHP的preg_match()从字符串中提取变量序列。 However, i'm not sure what to do if there are 2 variables that I need to match. 但是,如果我需要匹配2个变量,我不知道该怎么办。

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". 所以基本上我想知道如何提取两种模式:1)字符串的第一部分是“帮助”还是“业务”; 2)第二部分是“xyz123”还是“zyx321”。

The optional bonus question is what would the answer look like written in JS? 可选的奖金问题是答案看起来像是用JS编写的? I've never really figured out if regex (ie, the code including the slashes, /..../ ) are always the same or not in PHP vs. JS (or any language for that matter). 我从来没有真正弄清楚正则表达式(即包含斜杠的代码,/ /..../ )在PHP与JS(或任何语言)中是否总是相同或不相同。

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 . (help|business)基本上说,无论是匹配help还是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. 相同的正则表达式模式应该可以在Javascript中使用。 You don't need to tweak it. 你不需要调整它。

Yes, Kemal is right. 是的,凯末尔是对的。 You can use the same pattern in javascript. 您可以在javascript中使用相同的模式。

var str="business-321zyx@mysite.com";
var patt1=/(help|business)-(.*)@mysite.com/;
document.write(str.match(patt1));

Just pay attention at the return value from the functions that are different. 只需注意不同功能的返回值。 PHP return an array with more information than this code in Javascript. PHP在Javascript中返回一个包含比此代码更多信息的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM