Yasser Al Masri
Yasser Al Masri

Reputation: 53

Find string that does not contain some substring

I have a one liner string that looks like this:

My db objects are db.main_flow_tbl, 'main_flow_audit_tbl', main_request_seq and MAIN_SUBFLOW_TBL.

I want to use regular expressions to return database tables that start with main but do not contain words audit or seq, and irrespective of the case. So in the above example strings main_flow_tbl and MAIN_SUBFLOW_TBL shall return. Can someone help me with this please?

Upvotes: 0

Views: 1547

Answers (3)

Boris the Spider
Boris the Spider

Reputation: 61158

Here is a fully regex based solution:

public static void main(String[] args) throws Exception {
    final String in = "My db objects are db.main_flow_tbl, 'main_flow_audit_tbl', main_request_seq and MAIN_SUBFLOW_TBL.";
    final Pattern pat = Pattern.compile("main_(?!\\w*?(?:audit|seq))\\w++", Pattern.CASE_INSENSITIVE);
    final Matcher m = pat.matcher(in);
    while(m.find()) {
        System.out.println(m.group());
    }
}

Output:

main_flow_tbl
MAIN_SUBFLOW_TBL

This assumes that table names can only contain A-Za-Z_ which \w is the shorthand for.

Pattern breakdown:

  • main_ is the liternal "main" that you want tables to start with
  • (?!\\w*?(?:audit|seq)) is a negative lookahead (not followed by) which takes any number of \w characters (lazily) followed by either "audit" or "seq". This excludes tables names that contain those sequences.
  • \\w++ consume any table characters possesively.

EDIT

OP's comment they may contain numbers as well

In this case use this pattern:

main_(?![\\d\\w]*?(?:audit|seq))[\\d\\w]++

i.e. use [\\d\\w] rather than \\w

Upvotes: 2

nozzleman
nozzleman

Reputation: 9649

If the string matches

    ^main_(\w_)*(?!(?:audit|seq))

it should be what you want...

Upvotes: 0

crzbt
crzbt

Reputation: 183

String str
while ((str.startsWith("main"))&&!str.contains("audit")||!str.contains("seq")){
   //your code here
}

Upvotes: 0

Related Questions