0

I need to have a pattern to match the following strings

564 A 456
10 O 94 A 465 
234 A 654 O 1 
3 A 5697 O 68998 A 89789 A 665 
2 A 5646 A 123 A 123 
231 O 645 O 4565 O 564

Translation would...

Any number with any length (1 to *)

Followed by a space

Followed by any number with any length (1 to *)

Follwed by A or B

For example the following test would not be valid

A 465 //not begin with a number
564 AO 5645 //only A or O should appear Not both!
4564 A //not end in number
987 T 213 //invalid character T
1456 456 A 56 //invalid whitespace in first number
987 O 321654 987 //invalid whitespace in last number
12 A 456 O 132 A //not end in a number

At this moment i have this pattern \d+\s((A|O)\s\d+)*

But does not recognize all my valid string

2
  • Is string like "123" valid (it doesn't have letter and number after it)? Commented Dec 9, 2014 at 0:18
  • Your input doesn't match you description: number space number (A or B). Commented Dec 9, 2014 at 0:18

2 Answers 2

2

So you want to accept number (\d+ - one or more digits) which can be followed by one or more of
(A or O) number.

In that case your regex can look like \d+(\s[AO]\s\d+)+
but since \ is special in String its literal needs to be written as "\\d+(\\s[AO]\\s\\d+)+".

BTW, some of your lines in your example of valid strings ends with space so either trim this data before validation, or add \s? at the end of regex to also include this space.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! this pattern match all my tests.
0

You just need to include the space into the parenthesis, like this:

\d+(\s(A|O)\s\d+)*

And that should work like a charm!

Comments

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.