Cyber Ghost
Cyber Ghost

Reputation: 78

String.matches() return false unexpectedly.

I'm trying to write a program that interprets race results. However in order to do this I need to use regex to test if strings match a certain pattern using the String.matches(String regex) method. When using this methods some strings that I expect to return true, return false instead.

Using the following string as the regex pattern, some of the strings return true and other false when the should return true as well:

regex = "[ ]*[1-9]+[ ]+[a-zA-Z]+[ ]+[a-zA-Z]+[ ]+[a-zA-Z]+[ ]?[a-zA-Z]*[ ]?[a-zA-Z]*[ ]?[a-zA-Z]*[ ]?[a-zA-Z]*[ ]?[a-zA-Z]*[ ]?[1-9]+[ ]+[1-9]+[ ]+[0-9:.]+[ ]+"

These are some of the strings that return true with the string.matches(String regex) method:

" 1 Ryan Kepshire Crown Point 31 4 16:31 "
" 2 Matthew Mosak Crown Point 34 4 16:44 "
" 3 Dylan Wallace Crown Point 36 4 16:58 "
" 4 Nicholas Zak Hanover Central 51 6 17:08 "
" 5 Joshua Whitaker Crown Point 37 4 17:16 "
" 8 Collin Allen Hobart 64 8 17:23 "
" 9 Zachary Hoover Crown Point 29 4 17:29 "

These are some of the strings that return false with the string.matches(String regex) method:

" 6 Christopher Ramos River Forest 103 12 17:18 "
" 7 Boyer Hunter Lowell 78 10 17:20 "
" 10 Miguel Tapia Merrillville 98 11 17:32 "

I need help with determining why the bottom three strings fail the regex test while the top 7 pass it.

Upvotes: 1

Views: 111

Answers (1)

vks
vks

Reputation: 67968

[ ]*[0-9]+[ ]+[a-zA-Z]+[ ]+[a-zA-Z]+[ ]+[a-zA-Z]+[ ]?[a-zA-Z]*[ ]?[a-zA-Z]*[ ]?[a-zA-Z]*[ 
     ^ 
]?[a-zA-Z]*[ ]?[a-zA-Z]*[ ]?[0-9]+[ ]+[0-9]+[ ]+[0-9:.]+[ ]+
                             ^         ^    

Your regex does not allow 0 in integers.That is why it was failing.See here.

http://regex101.com/r/uH3tP3/5

I have modified it to accept 0.

Ex. [1-9]+ will not accept 10.

" 6 Christopher Ramos River Forest 103 12 17:18 " //fails due to 103

" 7 Boyer Hunter Lowell 78 10 17:20 " //fails due to 10

" 10 Miguel Tapia Merrillville 98 11 17:32 //fails due to 10

Upvotes: 5

Related Questions