Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java using regex to verify an input string

Tags:

java

regex

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 ?

like image 819
Tommy Ngo Avatar asked Apr 14 '13 22:04

Tommy Ngo


People also ask

How do you validate a string?

To validate a string for alphabets you can either compare each character in the String with the characters in the English alphabet (both cases) or, use regular expressions.

How do you check if a string matches a pattern in Java?

You can use the Pattern. matches() method to quickly check if a text (String) matches a given regular expression. Or you can compile a Pattern instance using Pattern. compile() which can be used multiple times to match the regular expression against multiple texts.


2 Answers

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.

like image 121
Boris the Spider Avatar answered Oct 10 '22 06:10

Boris the Spider


Why not just simply:

"[a-zA-Z\\s,]+"
like image 20
Petar Ivanov Avatar answered Oct 10 '22 06:10

Petar Ivanov