Xon
Xon

Reputation: 69

Regex to match specific word and ignore specific word

Currently I have a code like this

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

I have a few departments, for example:

How can I make the regex such that whenever I type this:

junior middle 

Will return people in Junior Management and Middle Management

management

Will return nothing, as I don't want it to print my whole management out.

junior top management

Will return people in Junior Management and Top Management

Thank you.

Edit 1: Currently I have something like this:

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)));
    }
}

Currently it works for all the 3 examples I listed above. However, it does not work if I type the word "management" 1st followed by the keywords. For example:

management top junior

This should return me the people in Top Management and Junior Management.

However, it does not return me anything. Is there anyway I can improve this code?

Upvotes: 1

Views: 98

Answers (1)

steffen
steffen

Reputation: 16938

How about this:

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);
}

Output:

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]

Upvotes: 1

Related Questions