Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java reg ex表达式,只需在逗号上拆分_Java_Regex_Groovy - Fatal编程技术网

Java reg ex表达式,只需在逗号上拆分

Java reg ex表达式,只需在逗号上拆分,java,regex,groovy,Java,Regex,Groovy,在这里测试代码。我想将我当前的正则表达式扩展为使用逗号拆分 String test = "This Is ,A Test" println(test) String noSpace = test.replaceAll("\\s","") println(noSpace) String[] words = noSpace.split("[^a-zA-Z0-9'-.]+") words.each { println(it) } 这将产生输出 This Is ,A Test ThisIs,A

在这里测试代码。我想将我当前的正则表达式扩展为使用逗号拆分

String test = "This Is ,A Test"
println(test)
String noSpace = test.replaceAll("\\s","")
println(noSpace)
String[] words = noSpace.split("[^a-zA-Z0-9'-.]+")

words.each {
   println(it)
}
这将产生输出

This Is ,A Test
ThisIs,ATest
ThisIs,ATest
我希望它在哪里产生输出

This Is ,A Test
ThisIs,ATest
ThisIs
ATest

有什么想法吗?谢谢

要基于逗号进行拆分,只需使用

String[] words = noSpace.split(",");

要基于逗号进行拆分,只需使用

String[] words = noSpace.split(",");
引自javadoc

请注意,角色类内部的元字符集实际上与角色类外部的元字符集不同。例如,正则表达式。在字符类中失去其特殊含义,而表达式-成为范围形成元字符

因此,您需要避开短跑:

String[] words = noSpace.split("[^a-zA-Z0-9'\\-.]+");
引自javadoc

请注意,角色类内部的元字符集实际上与角色类外部的元字符集不同。例如,正则表达式。在字符类中失去其特殊含义,而表达式-成为范围形成元字符

因此,您需要避开短跑:

String[] words = noSpace.split("[^a-zA-Z0-9'\\-.]+");

-.看起来很可疑。它看起来像是
包含在范围内。如果您有问题,并尝试使用正则表达式解决,则您有两个问题
split()。它看起来像是
包含在范围内。如果您有问题,并尝试使用正则表达式解决,则您有两个问题
split()
方法非常适用于此,或者您可以使用实际上不鼓励使用的
StringTokenizer
expression@Badmiral:如果您只想在逗号上拆分,请使用正确的作业工具(
split()
)。如果您有其他要求,请更新您的问题以说明这些要求。对于您当前提出的问题,正确答案是使用
split
。不要被诱惑去使用一些性感的东西(正则表达式),当一些简单的东西很好用的时候。我想增加我现在的正则表达式expression@Badmiral:如果您只想在逗号上拆分,请使用正确的作业工具(
split()
)。如果您有其他要求,请更新您的问题以说明这些要求。对于您当前提出的问题,正确答案是使用
split
。不要被诱惑去使用一些性感的东西(正则表达式),当一些简单的东西很好的工作。