【问题标题】:Regex or Other Method to Parse Obj-C Method Declaration正则表达式或其他方法来解析 Obj-C 方法声明
【发布时间】:2023-03-24 08:51:01
【问题描述】:

我有一个 Objective-C 方法的形式:

"hideAlertWithBundleId:(NSString *)bundleId uuid:(NSString *)uuid"

但它也可以写成这样的形式:

"hideAlertWithBundleId:   (NSString *)  bundleId         uuid: (NSString *) uuid"

我想提取:

["hideAlertWithBundleId:(NSString *)bundleId", "uuid:(NSString *)uuid"]

我在使用纯 Python 和正则表达式来实现这一点时遇到了麻烦,但我知道这是可能的。

请记住,括号中的值可以是任何东西。所以,我可能还需要解析:

"findImageWithKey:(id)arg1 inGroup:(id)arg2 andInfo:(img*)arg3"

可以假设字符串中没有换行符。该解决方案应该适用于具有任意数量参数的方法。

【问题讨论】:

  • 这可能不是正则表达式的工作。我不熟悉Objective-C,但我怀疑正确执行此操作需要能够匹配括号(或至少计算它们)。正则表达式不能做到这一点,或者至少,它们不能没有比 Python 的 re 模块更强大的扩展。
  • 如果字符串就像你的第一行(没有额外的空格),什么规则会告诉你字符串要在哪里被分割;即为什么在"bundleId""uuid:"之间的空间上?

标签: python regex parsing


【解决方案1】:

我对 Objective-C 不太熟悉,但如果我正确理解了这个问题,那么:

import re
for str in ["hideAlertWithBundleId:(NSString *)bundleId uuid:(NSString *)uuid",
    "hideAlertWithBundleId:   (NSString *)  bundleId         uuid: (NSString *) uuid",
    "-(BOOL)findImageWithKey:(id)arg1 inGroup:(id)arg2 andInfo:(img*)arg3"]:
    result = re.findall(r'((?:-\s*\(\w+\)\s*)?\w+)\s*:\s*(\(\w+\s*\*?\))\s*(\w+)', str)
    result2 = [i[0] + ":" + i[1] + i[2] for i in result]
    print(result2)

结果:

['hideAlertWithBundleId:(NSString *)bundleId', 'uuid:(NSString *)uuid']
['hideAlertWithBundleId:(NSString *)bundleId', 'uuid:(NSString *)uuid']
['-(BOOL)findImageWithKey:(id)arg1', 'inGroup:(id)arg2', 'andInfo:(img*)arg3']

【讨论】:

  • 谢谢,但我可能应该更具体一些......参数类型(在括号中)基本上可以是任何东西,而不仅仅是“NSString *”,所以这对于像这样的例子来说失败了:@ 987654323@
  • @YulkyTulky 感谢您的及时反馈。我已经根据您的更新调整了正则表达式。我不知道所有类型的 Objective-C 声明,如果我需要更多修改,请告诉我。
  • @YulkyTulky 很高兴知道它正在工作。如果我们需要其他修改,请告诉我。
猜你喜欢
  • 1970-01-01
  • 2011-05-11
  • 2014-02-02
  • 2017-11-07
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
  • 2013-02-10
  • 1970-01-01
相关资源
最近更新 更多