2

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

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()

我尝试使用大括号和空格进行一些简单的字符串拆分,但无法达到预期的结果。我该怎么办?

4

2 回答 2

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()

看起来很像您的示例数据:)

于 2012-09-14T12:11:00.753 回答
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();
} 
于 2012-09-14T09:40:57.977 回答