0

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?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Yasser Al Masri
  • 53
  • 1
  • 10
  • Maybe this links could help http://stackoverflow.com/questions/4813497/java-regex-case-insensitivity-not-working and http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word – holap Dec 11 '13 at 08:27
  • What did you try so far? Does it need to use a regular expression? – jwueller Dec 11 '13 at 08:29

3 Answers3

2

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

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
0
String str
while ((str.startsWith("main"))&&!str.contains("audit")||!str.contains("seq")){
   //your code here
}
crzbt
  • 183
  • 4
  • 14
0

If the string matches

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

it should be what you want...

nozzleman
  • 9,529
  • 4
  • 37
  • 58
  • Almost. You don't have the case insensitive flag. You have a start anchor so it won't find patterns _in_ `String`s; which is what the OP wants. And your match group would capture _up to_ the sequences the OP doesn't want. So rather than excluding names containing `seq` like `table_seq` this would capture `table_`. In short **test your code before posting**. – Boris the Spider Dec 11 '13 at 09:06