从字符串中提取方法键/参数

时间:2012-09-14 09:30:12

标签: java regex

我想要一个逻辑(可能是regexp),通过它我可以从下面的语句类型中提取方法键和参数。

RuleResult executeRule(RuleData, RuleProperties, Locale) { /* some key */ }
// result: executeRule(RuleData, RuleProperties, Locale)

RuleResult executeRule() { /* some key */ }
// result: executeRule()

executeRule(RuleData, RuleProperties, Locale) { /* some key */ }
// result: executeRule(RuleData, RuleProperties, Locale)

executeRule() { /* some key */ }
// result: executeRule()

static executeRule(RuleData, RuleProperties, Locale) { /* some key */ }
// result: executeRule(RuleData, RuleProperties, Locale)

static executeRule() { /* some key */ }
// result: executeRule()

我尝试了一些带有大括号和空格的简单字符串拆分,但无法达到所需的结果。我该怎么办?

2 个答案:

答案 0 :(得分:1)

在输入中使用replaceAll()和相应的参数:

input.replaceAll(".*(?<=^|\\s)(\\w+\\(.*?\\)).*", "$1");

此正则表达式匹配您要保留的组(在组1中使用“后视”),但匹配整个输入并将其替换为组1,从而保持,而不是替换,你想保留什么。

这是一些包含所有样本的测试代码:

public static void main(String[] args) throws Exception {
    String[] examples = { 
            "RuleResult executeRule(RuleData, RuleProperties, Locale) { /* some key */ }", 
            "RuleResult executeRule() { /* some key */ }",
            "executeRule(RuleData, RuleProperties, Locale) { /* some key */ }", 
            "executeRule() { /* some key */ }",
            "static executeRule(RuleData, RuleProperties, Locale) { /* some key */ }", 
            "static executeRule() { /* some key */ }" };
    for (String example : examples) {
        System.out.println(example + "\n// result: " + 
            example.replaceAll(".*(?<=^|\\s)(\\w+\\(.*?\\)).*", "$1") + "\n");
    }
}

输出:

RuleResult executeRule(RuleData, RuleProperties, Locale) { /* some key */ }
// result: executeRule(RuleData, RuleProperties, Locale)

RuleResult executeRule() { /* some key */ }
// result: executeRule()

executeRule(RuleData, RuleProperties, Locale) { /* some key */ }
// result: executeRule(RuleData, RuleProperties, Locale)

executeRule() { /* some key */ }
// result: executeRule()

static executeRule(RuleData, RuleProperties, Locale) { /* some key */ }
// result: executeRule(RuleData, RuleProperties, Locale)

static executeRule() { /* some key */ }
// result: executeRule()

看起来很像你的样本数据:)

答案 1 :(得分:0)

这看起来更像是你想要匹配的东西,而不是分裂它。

\w+\([^()]*\)

将匹配所有示例中的必需字符串。

<强>解释

\w+    # Match an alphanumeric "word"
\(     # Match an opening paren
[^()]* # Match any number of characters except parens
\)     # Match a closing paren

在Java中:

Pattern regex = Pattern.compile("\\w+\\([^()]*\\)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group();
}