首页 > 解决方案 > Remove whitespace in regex match

问题描述

I am using regex to read all the function names from the contract. Example

(void) function_name1(int, int);
(void) function_name2(int, int);
(void) function_name3(int, int);
(void) function_name4(int, int);

output expected:

function_name1
function_name2
function_name3
function_name4

I am using Regex "\)(.*?)\(" With this expression i am grouping the function name with space in begining of the function. Kindly help me how to ignore this space.

标签: regex

解决方案


这应该工作

(\w+)\s*\([^()]*\)

https://regex101.com/r/CzjFWt/1

<?php
$i = '(void) function_name1(int, int);
(void) function_name2(int, int);
(void) function_name3(int, int);
(void) function_name4(int, int);';

$r = '(\w_+)\s*\([^()]*\)';

preg_match_all('|' . $r . '|sm',
    $i,
    $o, PREG_PATTERN_ORDER);



foreach($o[1] as $v)echo  $v;

结果:

function_name1function_name2function_name3function_name4

或输出完整的结果数组:

echo var_export($o[1]);

php 中的示例:http: //sandbox.onlinephpfunctions.com/code/b3e387797e12853be040e00fcfd1d804629797b6

结果是:

array (
  0 => 'function_name1',
  1 => 'function_name2',
  2 => 'function_name3',
  3 => 'function_name4',
)

推荐阅读