简体   繁体   English

正则表达式查询要从字符串中分离并提取两个不同的集合?

[英]Regex Query To seperate and extract two different set from a string?

I need to extract two seperate information from a string. 我需要从字符串中提取两个单独的信息。

For example, 例如,

$string = 'int(5)';
//Now I need "int" and the text inside the brackets "5" seperately;
$datatype = ?
$varlength = ?

How to extract those information? 如何提取这些信息?

Use this regex 使用此正则表达式

^([az]+)\\(([0-9]+)\\)$

if (preg_match('~^([a-z]+)\(([0-9]+)\)$~i', 'int(5)', $matches)) {
  $datatype  = $matches[1]; // int
  $varlength = $matches[2]; // 5
}

EDIT 编辑

If you want to match more than just a number in the brackets, expand it as necessary: 如果要匹配的不只是方括号中的数字,请根据需要展开:

^([a-z]+)\(([0-9a-zA-Z, ]+)\)$ // numbers, letters, comma or space
^([a-z]+)\(([^)]+)\)$          // anything but a closing bracket

One way: 单程:

list($datatype, $varlength) = explode('(', trim($string, ')'));

This only works if there can be only one opening bracket. 仅在只有一个打开支架的情况下才有效。

Reference: list , explode , trim . 参考: listexplodetrim

In the case. 在这种情况下。 you want to match anything inside the brackets, use this 您想匹配方括号内的任何内容,请使用此

preg_match('/^([a-z]+)\(([a-zA-Z0-9\,]+)\)$/', 'enum(1,a)' , $matches);
print_r($matches);

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

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