正则表达式在结果中只需要两个空格

Regular expression to require exactly two spaces in result

在结果中只允许两个空格的正则表达式。示例:"one hundred dollars" 仅包含两个空格,如果超过 2 个空格,则条件应失败

示例:23455

包含超过 2 个空格,因此条件应该失败

使用\s检测白色space.

例如,要接受 "I am student" 或 "one hundred dollars" 你可以有..

/^ [A-Za-z]+ \s [A-Za-z]+ \s [A-Za-z]+ $/

虽然我不确定它是否有效..我没有检查。

这是执行您正在寻找的断言的 groovy 脚本。

//String sample to test both negative and positive tests

//This string should fail the test
​def string1 = 'two three thousand four hundred fifty five'

//this string should pass validation
def string2 = 'two three thousand'

//Expected space count
def expectedSpaces = 2
//Check for number of occurances of spaces in the given string
def group1 = (string1 =~​ /\s/)
def group2 = (string2 =~ /\s/ )

println "${string2} has ${group2.size()} spaces"
println "${string1} has ${group1.size()} spaces"

//Positive assertion
assert expectedSpaces == group2.size(), "${string2} failed assertion"
//You may find this failing as expected, so negative assertion
assert expectedSpaces != group1.size(), "${string1} failed assertion"​

你可以快速查看这个script

下面是正则表达式,它接受包含 3 个单词和 2 个 space

的字符串
/^([A-Za-z])+\s([A-Za-z])+\s([A-Za-z]+)$/

说明

  • ^ :字符串的开头
  • ([A-Za-z]+) :接受一个或一个单词 字符
  • \s : 白色 space
  • $:字符串结尾