lostcoderx
lostcoderx

Reputation: 27

Java Regex to accept anything within qualifier

I need a bit tricky java regex pattern to achieve the following.

Accept anything wihtin the qualifier say "$$" Something like below does most of the job:

Pattern rc = Pattern.compile("[\\$\\$].*[\\$\\$]");

This will accept strings like : "$$ANYTHING$$" , "$$A$@#$@NYTHING!!!$$" etc.

However I want to prohibit : $$abc$$xyz$$ as it contains "$$" in the middle! Please tell me a way to achieve this. Also $$$$xyz$$ and $$xyz$$$$ should be rejected

Upvotes: 1

Views: 124

Answers (2)

vks
vks

Reputation: 67968

^\\$\\$(?:(?!\\$\\$).)*\\$\\$$

Just add anchors and a negative lookahead to make sure $$ is not in middle.

See demo.

https://regex101.com/r/sH8aR8/8

The problem with your regex was [\\$\\$] will accept $ only one time as it is inside character class and without ^ and $ it will not be strict with boundaries. Also .* will accept anything that is why your second $ was getting accepted.

(?:(?!\\$\\$).)* makes sure $$ does not occur in between.

Edit

If count of $ is not fixed use

^\\$+(?:(?!\\$).)*\\$+$

Upvotes: 3

Bohemian
Bohemian

Reputation: 424983

Another way of looking at it is there are not 2 "$$" after the first $$:

^\\$\\$(?!(.*?\\$\\$){2}).*\\$\\$$

Upvotes: 0

Related Questions