Sriram Margapuri
Sriram Margapuri

Reputation: 53

Java Regular expression to restrict unwanted matchings

I want a java regular expr to match *T/N , *TA , *TI, *TA/O, *TI/O, *TA/N and *TI/N but should not accept *T. The following regular expression pattern

String pattern="\\*T[AI]?(/N|/O)?"; 

is matching all the conditions but its matching *T also. How can I prevent it from matching *T as well?

Upvotes: 1

Views: 51

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627536

Without more details, it seems you can use a positive lookahead to make sure there are at least 2 allowed characters after *T:

String pattern = "\\*(?=[TAI/]{2})T[AI]?(?:/[NO])?";

See the regex demo

The (?=[TAI/]{2}) positive lookahead will make sure there are 2 characters after *, either T, A, I or /.

Upvotes: 1

Related Questions