Hokyjack
Hokyjack

Reputation: 103

Restrict input to a certain pattern

I am creating an aplication in javaScript, but I am a bit confused of RegExp. I need to make user type into textArea desired form of string and let aplication to work with it, so I need to restrict the textArea input.

I need to field be like this: 760, 8,20, 50/3, 10,160/40, 3001

with optional spaces after comma, and optional number of items, where some of them can be optionaly with sufix (*/1...)

also i would like to have similar pattern which behave simillary but there could be prefixes like this:

st. 760,st. 8, st.20, st. 50/3, st. 10, st. 160/40, st. 3001

also with optional spaces. I would be really happy if someone could help me with making this regExp, because I am a real begginer in creating this...

I've tried the following regex ((\d+)|((\d+)/(\d+))),(\s?).

Thanks in advance!

Upvotes: 2

Views: 230

Answers (3)

cgledezma
cgledezma

Reputation: 622

I would use something like this:

^\d+(/\d+)?(\s*,\s*\d+(/\d+)?)*$

Then, for the second one:

^(st\.\s*)?\d+(/\d+)?(\s*,\s*(st\.\s*)?\d+(/\d+)?)*$

Remember, any time you can use the escape sequences, which will make your regex much clearer. So, instead of doing [0-9], use \d, and also use \s to accept all kinds of spaces (space, tab; etc).

Upvotes: 1

Ofir
Ofir

Reputation: 8362

I think

^([ ]*[0-9]+(/[0-9]+)?[ ]*\,)*([ ]*[0-9]+(/[0-9]+)?[ ]*)$

and

^([ ]*(st\. )?[0-9]+(/[0-9]+)?[ ]*\,)*([ ]*(st\. )?[0-9]+(/[0-9]+)?[ ]*)$

sound about right

Upvotes: 1

Xavier S.
Xavier S.

Reputation: 1157

I hope it could help you:

To select your field:

    ([0-9]+/[0-9]+[,]{0,1})|([0-9]+[,]{0,1}) 

To replace them:

    st\.\ &1&2 

By using sed command line :

    sed -e "s/([0-9]+/[0-9]+[,]{0,1})|([0-9]+[,]{0,1})/st\.\ &1&2/g"

Upvotes: 0

Related Questions