正则表达式匹配特定单词而忽略特定单词

时间:2018-10-09 17:58:43

标签: java regex

目前我有这样的代码

String[] departmentKeywords = trimmedArgs.split("\\s+");

我有几个部门,例如:

  • 初级管理人员

  • 中层管理

  • 高级管理人员

  • 最高管理层

我如何制作正则表达式,以便每次键入以下内容:

junior middle 

将遣返初级管理人员和中级管理人员

management

不会返回任何内容,因为我不希望它打印出我的整个管理层。

junior top management

将让初级管理人员和高层管理人员回国

谢谢。

编辑1: 目前我有这样的东西:

public class FilterDepartmentCommandParser implements Parser<FilterDepartmentCommand> {

    public FilterDepartmentCommand parse(String args) throws ParseException {
        String trimmedArgs = args.trim();
        trimmedArgs = trimmedArgs.replaceAll("(?i)management", "");
        if (trimmedArgs.isEmpty()) {
            throw new ParseException(
                    String.format(MESSAGE_INVALID_COMMAND_FORMAT, FilterDepartmentCommand.MESSAGE_USAGE));
        }

        String[] departmentKeywords = trimmedArgs.split("\\s+");

        return new FilterDepartmentCommand(new DepartmentContainsKeywordsPredicate(Arrays.asList(departmentKeywords)));
    }
}

目前,它适用于我上面列出的所有3个示例。但是,如果我先输入单词“ management” 1st,然后再输入关键字,则此方法无效。例如:

management top junior

这应该使我回到高层管理人员和初级管理人员中。

但是,它什么也没有回报我。无论如何,我可以改进此代码吗?

1 个答案:

答案 0 :(得分:1)

如何?

String[] departments = new String[] { "Junior Managment", "Middle Management", "Senior Management", "Top Management" };
String[] tests = new String[] { "management", "age", "junior", "mid", "op management", "uni middle", "junior middle management" };
for (String searchString : tests) {
    List<String> searchWords = new ArrayList<>(Arrays.asList(searchString.split(" ")));
    searchWords.replaceAll(String::toLowerCase);
    searchWords.removeIf("management"::contains);
    Set<String> matches = new HashSet<>(departments.length);
    matches.addAll(Stream.of(departments)
            .filter(d -> searchWords.stream().anyMatch(d.toLowerCase()::contains))
            .collect(Collectors.toSet()));

    System.out.println(searchString + ": " + matches);
}

输出:

management: []
age: []
junior: [Junior Managment]
mid: [Middle Management]
op management: [Top Management]
uni middle: [Middle Management, Junior Managment]
junior middle management: [Middle Management, Junior Managment]