在您的输入中使用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()
看起来很像您的示例数据:)