Reputation: 27
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
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.
If count of $
is not fixed use
^\\$+(?:(?!\\$).)*\\$+$
Upvotes: 3
Reputation: 424983
Another way of looking at it is there are not 2 "$$" after the first $$:
^\\$\\$(?!(.*?\\$\\$){2}).*\\$\\$$
Upvotes: 0