5

I need a regex pattern that accepts only comma separated values for an input field.

For example: abc,xyz,pqr. It should reject values like: , ,sample text1,text2,

I also need to accept semicolon separated values also. Can anyone suggest a regex pattern for this ?

4

5 回答 5

8

最简单的形式:

^\w+(,\w+)*$

演示在这里。


我只需要限制字母。我怎样才能做到这一点 ?

使用正则表达式(包括示例 unicode 字符范围):

^[\u0400-\u04FFa-zA-Z ]+(,[\u0400-\u04FFa-zA-Z ]+)*$

这个演示在这里

示例用法:

public static void main (String[] args) throws java.lang.Exception
{
    String regex = "^[\u0400-\u04FFa-zA-Z ]+(,[\u0400-\u04FFa-zA-Z ]+)*$";

    System.out.println("abc,xyz,pqr".matches(regex)); // true
    System.out.println("text1,text2,".matches(regex)); // false
    System.out.println("ЕЖЗ,ИЙК".matches(regex)); // true
}

Java 演示。

于 2013-06-26T04:05:20.530 回答
2

尝试:

^\w+((,\w+)+)?$

您可以使用在线正则表达式测试器进行练习。例如,http://regexpal.com/

于 2013-06-26T04:07:16.333 回答
1

Try the next:

^[^,]+(,[^,]+)*$

You can have spaces between words and Unicode text, like:

word1 word2,áéíóú áéíúó,ñ,word3
于 2013-06-26T04:10:29.250 回答
1

The simplest regex that works is:

^\w+(,\w+)*$

And here it is as a method:

public static boolean isCsv(String csv) {
    return csv.matches("\\w+(,\\w+)*");
}

Note that String.matches() doesn't need the start or end regex (^ and $); they are implied with this method, because the entire input must be matched to return true.

于 2013-06-26T04:10:50.570 回答
0

我想你想要这个,根据你的评论只想要字母(我假设你的意思是字母)

^[A-Za-z]+(,[A-Za-z]+)*$

于 2013-06-26T04:15:37.437 回答