Caesar
Caesar

Reputation: 179

Java script regex grouping

I am a newbie in java script regex. I need to validate one of the fields in web page in my project using java script regex. --The field should not allow any special characters except ("/"). --Also The field shouldn't allow any word starting with a "/" or ending with "/".But in between "/" is allowed. --Also there is a restriction that it should not allow more than one consecutive slash. ---The field should allow single characters to pass as well

Basically the words which are allowed are :-

data
data/sdsd
d/s/s/sss

those which are not allowing are:-

/data
or //data
or data/
or data////
or data/////data

I though of two regex 1. (^[\w]+.*[^/]$) i.e allow word starting with alphanumeric character & also checkit should not allow the word to end with "/".

I know it's not a good regex(in between it'll allow multple number of "/" also special characters are also not taken care of) but the main problem with it is that it rejects single character, so please if any one can help me in modifying this regex to allow with single characters, it'll be of great help

  1. [\w]+([/][\w]+)* i.e. i wanted to create a regex which will allow any number of repetition of alphanumberic characters but if it sees a slash make sure that it is followed by a alphanueric character. & i read in internet that "()" is used to group the characters so i thought ([/][\w]+)* will act as group which will allow:-

    /s, /sss , /dadada

And the metacharacter "*" will make sure that it will be repeated any number of times. But the problem with this is it is not grouping [/] and [\w]+, them rather it is allowing words ending with "/" Please if anyone can help me with this it'll be of great help. Thnaks in advance!!

Upvotes: 1

Views: 108

Answers (3)

maja
maja

Reputation: 18034

This should solve your Problem:

^(\w(([/]?\w)*\w)?)$

The regexp says:

A match always has to start with a word-character.

If there are more than 1 characters, the last one also has to be a word-character.

All chacaters in-between are either a /, followed by a word character, or only a single word-character, short: ([/]?\w)*

Adding a plus might give you some performance improvements:

^(\w(([/]?\w+)*\w)?)$

Upvotes: 0

Joel
Joel

Reputation: 11

I think will be help solve your problem. The lazy quantifier on the group and the beginning and ending references to help anchor the whole thing seem to work.

/^\w([//]?\w+)*?$/ig

Upvotes: 1

brandonscript
brandonscript

Reputation: 72845

This probably isn't the most efficient, but it should get you started. Javascript's regex engine doesn't support lookbehinds, so that makes it a little more complicated.

^([a-z]+([a-z]|\/(?![\/]))*[a-z]|[a-z])$

http://regex101.com/r/iA9kC6

You'll also probably want to use the case-insensitive modifier, so the result (with / delimiters) looks like this:

/^([a-z]+([a-z]|\/(?![\/]))*[a-z]|[a-z])$/i

Upvotes: 4

Related Questions