0

I need to validate that the text input in my rails form has contains one or more alphanumerics with specific format separated by comma.

For example the alphanumeric should be either two letters + seven numbers + one letter + one number or two letters + 11 numbers + one letter + one number . And these alphanumerics must be separated by comma (,)

US6174724B1 , US20010002490A1 (This is a valid one)

ruby , rails (This is an invalid one)

How can I build a ruby regular expression that checks if (these alphanumerics have specific format) AND if (they are separated by comma)

1 Answer 1

3

You could use this:

PATTERN

/^(?:(?:^| , )([A-Z]{2}(?:\d{7}|\d{11})[A-Z]\d)\b)+?$/

And you will have your alphanumerics in specific format in capture group 1.

INPUT

US6174724B1 , US20010002490A1 (This is a valid one)

ruby , rails (This is an invalid one)

OUTPUT

Match 1: US6174724B1 
Group 1: US6174724B1

Match 2:  , US20010002490A1 
Group 1: US20010002490A1
Sign up to request clarification or add additional context in comments.

8 Comments

It works :) . Two questions only , 1) I had to add a forward slash in the beginning and in the end of the regex because otherwise I had an error when I tried to load my page. Why is that ? 2. What do you mean that the alphanumerics will be available in capture group 1 ?
@Stefanos it depends on the language, usually you should add slash at the beginning and at the end of the pattern just as you did : ) My 'native' language is C# which doesn't require me to do this, anyway added them to the answer as you are using ruby : )
nice :) , and what do you mean that the alphanumerics will be available in capture group 1 ?
@Stefanos I'm not sure how about ruby but usually using regex you can capture certain groups within one match, well sounds bit complicated huh? The capture group is inside parenthesis ( ), so it will be possible to access certain group via code without including unnecessary things. Maybe this link will explain it better and more briefly www.regular-expressions.info also I have found this question in ruby about capture groups link
@Stefanos Ok added the string boundries at the beginning and at the end of the pattern, it should work as intented now.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.