我有一个单行字符串,如下所示:
我的db对象是db.main_flow_tbl,'main_flow_audit_tbl', main_request_seq和MAIN_SUBFLOW_TBL。
我想使用正则表达式返回以 main 开头但不包含单词 audit 或 seq 的数据库表,而不管案子。因此,在上面的示例中,字符串 main_flow_tbl 和 MAIN_SUBFLOW_TBL 将返回。有人可以帮帮我吗?
答案 0 :(得分:2)
这是一个完全基于正则表达式的解决方案:
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());
}
}
输出:
main_flow_tbl
MAIN_SUBFLOW_TBL
这假设表名只能包含A-Za-Z_
,其中\w
是简写。
模式分解:
main_
是您希望表格以(?!\\w*?(?:audit|seq))
是一个负面预测(未跟随),它接受任意数量的\w
个字符(懒惰),后跟“audit”或“seq”。这排除了包含这些序列的表名。\\w++
占用任何表格字符。修改强>
OP的评论他们也可能包含数字
在这种情况下使用此模式:
main_(?![\\d\\w]*?(?:audit|seq))[\\d\\w]++
即。使用[\\d\\w]
而不是\\w
答案 1 :(得分:0)
String str
while ((str.startsWith("main"))&&!str.contains("audit")||!str.contains("seq")){
//your code here
}
答案 2 :(得分:0)
如果字符串匹配
^main_(\w_)*(?!(?:audit|seq))
它应该是你想要的......