17

g.:

String string="Marc Louie, Garduque Bautista";

I want to check if a string contains only words, a comma and spaces. i have tried to use regex and the closest I got is this :

String pattern = "[a-zA-Z]+(\\s[a-zA-Z]+)+";

but it doesnt check if there is a comma in there or not. Any suggestion ?

2
  • 2
    "a" comma, or commas? Commented Apr 14, 2013 at 22:47
  • What does a "word" mean to you? I see that your example has names, in which case "Skłodowska-Curie" would also be a "word" but it contains dash which is outside [a-zA-Z] range. There might be a couple of more such exceptional cases (eg. diacritics as in the example above). Commented Apr 22, 2013 at 7:37

5 Answers 5

30

You need to use the pattern

^[A-Za-z, ]++$

For example

public static void main(String[] args) throws IOException {
    final String input = "Marc Louie, Garduque Bautista";
    final Pattern pattern = Pattern.compile("^[A-Za-z, ]++$");
    if (!pattern.matcher(input).matches()) {
        throw new IllegalArgumentException("Invalid String");
    }
}

EDIT

As per Michael's astute comment the OP might mean a single comma, in which case

^[A-Za-z ]++,[A-Za-z ]++$

Ought to work.

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

Comments

2

Why not just simply:

"[a-zA-Z\\s,]+"

2 Comments

\s matches more than just spaces.
\s matches all spaces (e.g. tabs, etc.)
1

Use this will best

"(?i)[a-z,\\s]+"

Comments

0

If you mean "some words, any spaces and one single comma, wherever it occurs to be" then my feeling is to suggest this approach:

"^[^,]* *, *[^,]*$"

This means "Start with zero or more characters which are NOT (^) a comma, then you could find zero or more spaces, then a comma, then again zero or more spaces, then finally again zero or more characters which are NOT (^) a comma".

Comments

-1

To validate String in java where No special char at beginning and end but may have some special char in between.

String strRGEX = "^[a-zA-Z0-9]+([a-zA-Z0-9-/?:.,\'+_\\s])+([a-zA-Z0-9])$";
        String toBeTested= "TesADAD2-3t?S+s/fs:fds'f.324,ffs";
        boolean testResult= Pattern.matches(strRGEX, toBeTested);
        System.out.println("Test="+testResult);

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.