简体   繁体   English

使用preg_match在php中使用正则表达式

[英]regex in php using preg_match

I am trying to make a php file so it can accept word for a regex (a+b)(ab+ba)* i am using preg_match and so far ive come up with this 我正在尝试制作一个php文件,以便它可以接受正则表达式(a + b)(ab + ba)*的单词,我正在使用preg_match,到目前为止,我已经提出了这个建议

    $subject = "a+b";
    $pattern = '(([a]{1}\+[b]{1})?([ab]{1}\+[ba]{1}))';
    preg_match($pattern, $subject, $matches);
    print_r($matches);

I am not sure if i completely understand how it works but its been few hours now I am trying to figure out.. how do i make it so it fullfills my condition 我不确定我是否完全理解它的工作原理,但现在已经花了几个小时了。

I want to match (a+b)(ab+ba)* where the first bracket (a+b) is required and the * on the second bracket (ab+ba) means that there could be zero or multiple instances of it. 我想匹配(a + b)(ab + ba)*,其中第一个括号(a + b)是必需的,第二个括号(ab + ba)上的*表示它可能有零个或多个实例。 so it should work like this 所以它应该像这样工作

   $subject= "(a+b)"
   Match


   $subject= "(a+b)(ab+ba)"
   Match


   $subject= "(a+b)(ab+ba)(ab+ba)"
   Match

   $subject= "(ab+ba)"
   No Match

   $subject= ""
   No Match

In (([a]{1}\\+[b]{1})?([ab]{1}\\+[ba]{1})) (([a]{1}\\+[b]{1})?([ab]{1}\\+[ba]{1}))

[a]{1} (1 character in a character class ) can be written as a [a]{1}在1个字符的字符类 )可以写为a

[b]{1} can be written as b [b]{1}可以写成b

[ab] (2 characters in a character class) means a or b [ab] (字符类中的2个字符)表示a或b

I think you have to escape the opening parenthesis \\( , or else you would start a capturing group. 我认为您必须转义开头括号\\( ,否则您将启动捕获组。

If I am not mistaken, this might match what you are looking for: 如果我没记错的话,这可能与您要寻找的内容相符:

^\\(a\\+b\\)(?:\\(ab\\+ba\\))*$

The second part is in a non capturing group (?:\\(ab\\+ba\\))* and repeated zero or more times. 第二部分位于非捕获组(?:\\(ab\\+ba\\))*并重复零次或更多次。

Php test ouput php测试输出

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

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