如何在Java中定义匹配(...)的正则表达式并拆分字符串提取方法名?
问题描述
需要拆分一个包含方法名、类名及其他信息的字符串,其中方法与类通过冒号分隔。对于方法,仅需提取名称,无需保留参数部分,需要定义匹配(...)(...代表任意内容)的正则表达式。
已尝试的方案及结果
方案一
代码:
String str = "M:org.apache.commons.math3.genetics.CycleCrossover:mate(org.apache.commons.math3.genetics.AbstractListChromosome,org.apache.commons.math3.genetics.AbstractListChromosome) (O)java.util.HashSet:<init>(int)"; String[] arr = line.split(":|[(&&[a-z|A-Z]&&)]");
输出:
M org.apache.commons.math3.genetics.CycleCrossover mate(org.apache.commons.math3.genetics.AbstractListChromosome,org.apache.commons.math3.genetics.AbstractListChromosome) (O)java.util.HashSet <init>(int)
方案二
代码:
String[] arr = line.split(":| |[(]|[)]");
输出:
M org.apache.commons.math3.genetics.CycleCrossover mate org.apache.commons.math3.genetics.AbstractListChromosome,org.apache.commons.math3.genetics.AbstractListChromosome O java.util.HashSet <init> int
期望输出
M org.apache.commons.math3.genetics.CycleCrossover mate java.util.HashSet <init>
解决方案
实现思路
- 先移除所有方法的参数部分(即
(...)结构); - 再按冒号和
(O)标记拆分字符串,最后过滤空内容。
代码示例
String line = "M:org.apache.commons.math3.genetics.CycleCrossover:mate(org.apache.commons.math3.genetics.AbstractListChromosome,org.apache.commons.math3.genetics.AbstractListChromosome) (O)java.util.HashSet:<init>(int)"; // 移除所有方法参数部分 String cleanedStr = line.replaceAll("\\([^)]*\\)", ""); // 拆分分隔符:冒号、(O)及前后空白 String[] resultArr = cleanedStr.split(":|\\s*\\(O\\)\\s*"); // 输出结果,过滤空字符串 for (String part : resultArr) { String trimmedPart = part.trim(); if (!trimmedPart.isEmpty()) { System.out.println(trimmedPart); } }
正则说明
\\([^)]*\\):匹配任意以(开头、)结尾的内容,精准移除方法参数;:|\\s*\\(O\\)\\s*:匹配冒号,或(O)及其前后的空白,作为拆分的分隔符。
内容的提问来源于stack exchange,提问作者Somaiyah Sultani
相关产品推荐
相关产品推荐

