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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败