Reputation: 23
I need a Regex that matches these Strings:
Test 1
Test 123
Test 1.1 (not required but would be neat)
Test
Test a
But not the following:
Test 1a
I don't know how this pattern should look like that it allows text or whitespace at the end but not if there is a number before.
I tried this one
^.*([0-9])$
(matches only Test 1
, but not for example Test
or Test a
)
and this one
^.*[0-9].$
(matches only Test 1a
, but not for example Test
or Test 1
)
but they don't match what I need.
Upvotes: 2
Views: 94
Reputation: 991
As per your strings in your question (and your comments):
^\w+(\s[a-z]|\s\d+(\.\d+)?)?$
Upvotes: 0
Reputation: 4504
Another pattern for you to try:
^(Test(?:$|\s(?:\d$|[a-z]$|\d{3}|\d\.\d$)))
Upvotes: 0
Reputation: 11032
This is working for all cases you provided
^\w+(\s(\d+(\.\d+)?|[a-z]))?$
Regex Breakdown
^ #Start of string
\w+ #Match any characters until next space or end of string
(\s #Match a whitespace
(
\d+ #Match any set of digits
(\.\d+)? #Digits after decimal(optional)
| #Alternation(OR)
[a-z] #Match any character
)
)? #Make it optional
$ #End of string
If you also want to include capital letters, then you can use
^\w+(\s(\d+(\.\d+)?|[A-Za-z]))?$
Upvotes: 1