Java - 用单词和符号分割

我有一个字符串,比如String str = "void Write(int *p,int a)"我想获取函数名称“str”和参数名称“*p”、“a”。但是,我不知道有多少参数。

我写过"int\\s+|void\\s+|string\\s+|float\\s+|double\\s+|char\\s+\\(,\\)"正则表达式。

第 1 部分 =Write( 第 2 部分 =*p, 第 3 部分 =a)

正则表达式的最后一部分\\(,\\)是删除分号和括号。但如你所见,它失败了。我必须使用第二次拆分还是有其他方法?


天涯尽头无女友
浏览 67回答 1
1回答

喵喔喔

这将是一个两步过程第 1 步:提取函数名称和所有参数第 2 步:从所有参数列表中提取每个参数名称步骤1:让我们将此正则表达式^\S+\s+([^(]+)\(([^)]+)*应用于此字符串void Write(int *p,int a, int b, str *v)此测试字符串^&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# start of string\S+&nbsp; &nbsp; &nbsp; &nbsp;# one or more occurence of any non space charactcers&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # matches `void`\s+&nbsp; &nbsp; &nbsp; &nbsp;# one or more occurence of a space character&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # matches the space after `void`([^(]+)&nbsp; &nbsp;# all characters until opening parenthesis&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # matches `Write` and capture it\(&nbsp; &nbsp; &nbsp; &nbsp; # literally matches opening parenthesis([^)]+)&nbsp; &nbsp;# matches all characters till closing parenthesis is encountered&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # matches arguments signature i.e. `int *p,int a, int b, str *v`*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# matches zero or more occurrence of last capturing group&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # last capturing group is string between the parenthesis&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # so this star handle the corner case when the argument list is empty更多详情:https ://regex101.com/r/0m1vs9/2第2步现在对参数列表 ( int *p,int a, int b, str *v) 应用这个\s*\S+\s+([^,]+),?带有全局修饰符的正则表达式这种模式匹配逗号之间的文本,所以让我们解释假设相同的模式\s*&nbsp; &nbsp; &nbsp; # matches zero or more occurrences of a space character&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# this will match any spaces after comma e.g. `int b,<space> str`\S+&nbsp; &nbsp; &nbsp; # one or more occurrence of non space character&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# matches argument type, i.e. `int`\s+&nbsp; &nbsp; &nbsp; # one or more occurrence of space characters&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# matches the space between argument name and type, e.g. `int<space>b`([^,]+)&nbsp; # capture all characters till comma&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# this matches the actual argument name&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# and also matches any spaces after it,?&nbsp; &nbsp; &nbsp; &nbsp;# zero or one occurrence of a comma&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# this ensures that the argument name is immediately followed by a comma&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# this also handles the case for the last argument which doesn't have any comma after it更多详情:https ://regex101.com/r/9ju60l/1希望有帮助
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java