solejnik
solejnik

Reputation: 25

Filter regex not valid

i have a problem with text pattern in java. I want to use this pattern to validate inserted text to filter text in table. This text can contain "!"(not) and "*"(like?). I have also possibility to use & (and) and |(or) to join logical expressions together with text operations (endsWith, startsWith, contains). What exactly i want is to avoid inserting not validate text. Examples for not valid text

-
!
!*
*!
!!
**
*!
!*
A**
**A
*A&
&A*

And examples for valid text

A*
*A
*-*
!a|b&c|!ab
!a|*b&c*|!*ab
!*aa*|*sdb&casd*|!*aasdb*
!*aa|*sdb&casd*|!*aasdb*
S*|L*

With my pattern "\s*(!?\*?[^&\|]*[&\|])*!?\*?[^&\|]*\*?\s*" both groups are valid. I tried difference combinations but without success. Any ideas?

Upvotes: 1

Views: 77

Answers (1)

SamWhan
SamWhan

Reputation: 8332

Your description of what you wan't, and your examples aren't absolutely clear. For example, *-* is valid indicating - is a valid filter character, so why is just a - invalid? That's not logical.

But from what I can gather, you're after something like this:

\s*(?:!?\*?[^&|*!\n]+\*?[&|])*!?\*?[^&|*!\n]+\*?\s*

It uses a non capturing group for the first, optional part. If this is present it ends with a | or a &. Then follows the non optional part, which is the same, except for not having the terminating operator:

An optional !, possibly followed by an optional *. Then any character but a &, |, ! or newline - at least one. Finally an optional * can follow.

See it here at regex101.

Note that not anchoring to start and end (^ and $) implies using java's matches method, that does that for you. Using another method, or another regex flavor, will require those to be added, or this will match basically anything.

Upvotes: 1

Related Questions