Andrew MacRobert
Andrew MacRobert

Reputation: 23

Regex to validate a character at start and end but also multiple occurences in between

I need to prevent a character / occurring in a java string at the start and end and also // anywhere with only alphanumerics allowed along with .,()?'+/

I have this ^[^/]?([\w\-\?:().,'+]/?)*[^/]$

The main problem is that it allows invalid characters # and ## at the start.

Also tried this ^[^/]?([^\W_\-\?:().,'+]/?)*[^/]$ to remove the _ underscore issue caused by \w

So these are invalid

/
A//A
A/
#
##

But these are valid

A/A
A/A.,()+A

Upvotes: 1

Views: 40

Answers (3)

Alan Moore
Alan Moore

Reputation: 75222

Give it a chance to be simple. There's no need for negated character classes ([^X] - "anything but X") or negative lookarounds ((?<!X), (?!X) - "nothing, or not X"). You know exactly which characters are allowed everywhere in the string, so spell it out:

^[A-Za-z0-9?:().,'+-]+(?:/[A-Za-z0-9?:().,'+-]+)*$

You don't need to specify that the slash (/) can't be first, just list the characters that can. And when a slash does appear, make sure it's followed by at least one of the other allowed characters. And the anchors (^ and $) ensure nothing else gets in.

Upvotes: 0

james jelo4kul
james jelo4kul

Reputation: 829

you can also try this

^[^/#]?([\w\-\?:().,'+]/?)*[^/#]$

If you explicitly want # not to be include at the beginning or end, just add it in your first and last character classes []

See demo https://regex101.com/r/vV1wW6/43

Upvotes: 0

vks
vks

Reputation: 67968

^(?!/)([\w-\?:().,'+]/?)*(?<!/)$

You can use lookarounds here which 0 width assertions.See demo.

https://regex101.com/r/vV1wW6/41

Upvotes: 1

Related Questions