Reputation: 31
So I created a program that would bring go through an input file and only pull the lines with 2 words in them. I then am trying to pull only the lines with ONLY letters. If there is any number I need it to fail. So far after researching I have come up with the code below and am just stuck on how else to get "test 123" to fail. It keeps passing.`Below is the call for my match function and the function itself. * *
else if (line.matches("[\\w\\-.]{2,} [\\w\\-.]{2,}"))
{
getmatch();
}
public static String getMatch()
{
if (line.matches("/[a-zA-Z]+/g") )
{
match=line;
}
return match;
}
Upvotes: 0
Views: 124
Reputation: 521053
I would use the following general pattern to match lines with two letter-only words:
\s*[A-Za-z]+\s+[A-Za-z]+\s*
This pattern will also take into account any amount of whitespace on either side of the two words, or in between them. Note that String#matches
by default includes starting and ending anchors around the input regex pattern, so we don't need to explicitly include them, though I did include them in the demo below.
You would use this pattern as:
String input = " Hello World ";
if (input.matches("\\s*[A-Za-z]+\\s+[A-Za-z]+\\s*")) {
System.out.println("Found a match!");
}
Upvotes: 1