View Full Version : [JAVA] string.matches - regular expression
tijean
05-25-2006, 01:02 PM
Hello,
I want a given string to match a certain pattern and I am using the following function
public boolean matches(String regex) from java.lang.String
The constraints the strings have to satisfy are the following
- at least 2 letter a-zA-z
- zero or more times an apostrophe (')
- zero or more times a space
for example James o'Hara is valid string.
The problem is I can't find the right pattern/regular expression.
I tried this: string.matches([a-zA-Z]{2,}[ ']*) but the example didn't work.
Can anyone help me? I am using eclipse and Java5.0
Thanks Tijean
Melon00
05-25-2006, 08:00 PM
Can you give examples of input-output combinations?
Spookster
05-25-2006, 08:53 PM
Is the purpose of your homework assignment to understand the use of regular expressions and develop a regex to match that pattern or is this just part of a bigger assigment and you wanted to use regular expressions so solve that part?
tijean
05-25-2006, 09:30 PM
Is the purpose of your homework assignment to understand the use of regular expressions and develop a regex to match that pattern or is this just part of a bigger assigment and you wanted to use regular expressions so solve that part?
it's just a little part. And I already used it for other patterns (only letters and number en dot) and it worked wel. But on this one I just can't find the right expression.
Can you give examples of input-output combinations?
I don't really understand your question but the following inputs strings should give TRUE
ab
abC
abC'
abC '
abc 'Zyx
....
and the following false
a - not enough letters
a' - not enough letters
a ' - not enough letters
b8 - number not allowed
b.C - other signs not allowed
....
Thanks for helping.
rpgfan3233
05-26-2006, 12:12 AM
The regex I used was
[a-zA-Z]{2,}[a-zA-Z ']*
It seemed to work:
Ouch this totally 'sux0rz - false (numbers)
Ouch this totally 'sux.rz - false (improper character)
Ouch this totally 'suxorz - true
a - false (not enough beginning letters)
a' - false (not enough beginning letters)
a ' - false (not enough beginning letters)
a b' - false (not enough beginning letters)
a'b - false (not enough beginning letters)
ab' - true
ab ' - true
/** Edit
The reason that you were having problems is because you weren't allowing for letters after a space or after an apostrophe. The regex string you created assumes that there is no input other than a space or an apostrophe after a space or an apostrophe.
*/
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.