markbernard markbernard - 16 days ago 7
Java Question

Regular expression to return results that do not match selection

I work on a product that provides a Java API to extend it.

The API provides a function which
takes a Perl regular expression and
returns a list of matching files.

I want to filter the list to remove all files that end in

.xml
,
.xsl
and
.cfg
; basically the opposite of
.*(\.xml|\.xsl|\.cfg)
.

I have been searching but I haven't been able to get anything to work yet.

I tried
.*(?!\.cfg)
and
^((?!cfg).)*$
and
\.(?!cfg$|?!xml$|?!xsl$)
.

I don't know if I am on the right track or not.

Note



I know the regex systems are similar, but I can't get a Java regex working either.

Answer

You may use

^(?!.*\.(x[ms]l|cfg)$).+

See the regex demo

Details:

  • ^ - start of a string
  • (?!.*\.(x[ms]l|cfg)$) - a negative lookahead that fails the match if any 0+ chars other than line break chars (.*) are followed with xml, xsl or cfg ((x[ms]l|cfg)) at the end of the string ($)
  • .+ - any 1 or more chars other than linebreak chars. Might be omitted if the entire string match is not required (in some tools it is required though).