duanhuantong8278 2018-10-17 18:02
浏览 77
已采纳

正则表达式:拆分函数调用参数

Running into this problem and I've been searching for days. I'm using PHP to parse formulas for a platform.

A formula could be something like:

object.Field

ADD(object.NumberOfTHings, object.NumberOfThings)

object.DoSomething(ADD(object.NumberOfTHings, object.NumberOfThings), 'words!')

The idea is, it can nest many levels. Users can include quotes (double and single) as well.

I'm working on a function that will return each parameter at the highest level. So

object.DoSomething(ADD(object.NumberOfTHings, object.NumberOfThings), 'words!')

Will need to return the following array:

  • ADD(object.NumberOfTHings, object.NumberOfThings)
  • 'words!'

We then go back and parse each parameter appropriately (some are object calls, function calls, etc.). I'm open to parsing it all at once, but figured that would just be more complicated.

My current regex is as follows:

\(?'pullsinglequotes'\'.+?\')|(?'pulldoublequotes'\".+?\")|(?'pullfunctions'[^,]\(([^()]|(?R))*\))\

It MOSTLY works, but has two issues:

  1. Won't return objects yet (ex. if I reference object.Field as a parameter).
  2. Only includes the last letter of a function.

Here's a REGEXR with the issue: https://regexr.com/41e20

I've tried many different variations of REGEX and each has its downsides.

My question is: Does anyone have enough regex knowledge to solve those two issues? If so, any help would be greatly appreciated.

Update If anyone is interested, this following was my final regex.

/(?'pullsinglequotes'\'.+?\')|(?'pulldoublequotes'\".+?\")|(?'pullfunctions'\b[\w.]+\s*\(([^()]|(?R))*\))|(?'pullvars'\w+(?:\.\w+)?)/
  • 写回答

1条回答 默认 最新

  • doudao1922 2018-10-17 18:18
    关注

    Your pullfunctions is only matching one character that's not a , followed by a parens. Allow it to repeat and precede it with a word boundary.

    For the vars and objects, just use a repeating word character with an optional dot-separated part. You can adjust this to a character group to allow other characters like - or _.

    Full regex:

    (?'pullsinglequotes'\'.+?\')|(?'pulldoublequotes'\".+?\")|(?'pullfunctions'\b[\w]+\s*\(([^()]|(?R))*\))|(?'pullvars'\w+(?:\.\w+)?)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划