正则表达式模式以检测有效载荷*模式

时间:2018-07-19 08:52:06

标签: regex scala

我要验证所有具有'payload。*'的字符串,即该字符串必须以'payload'开头,后跟一个句点(。),然后至少一个字符。

示例:-

Input1 :- payload.Hello     Output1 :-> Valid
Input2 :- Hipayload.Hello     Output1 :-> InValid
Input3 :- payload.H     Output1 :-> Valid
Input4 :- payload.     Output1 :-> InValid

3 个答案:

答案 0 :(得分:2)

您可以使用x.matches(y)(其中xy都是字符串)来匹配Scala中的Regex模式(或使用“原始”字符串):

scala> val regex: String = "^payload\\..+"
regex: String = ^payload\..+

scala> val regexAltRaw: String = raw"^payload\..+"
regexAltRaw : String = ^payload\..+

scala> val regexAltTripleQuotes: String = """^payload\..+"""
regexAltTripleQuotes : String = ^payload\..+

scala> "".matches(regex)
res0: Boolean = false

scala> "payload.Hello".matches(regex)
res1: Boolean = true

scala> "Hipayload.Hello".matches(regex)
res2: Boolean = false

scala> "payload.H".matches(regex)
res3: Boolean = true

scala> "payload.".matches(regex)
res4: Boolean = false

解释模式:

  • ^payload-以“有效载荷”开头
  • \\.-“。从字面上看(不使用“原始”字符串,Scala要求您使用双反斜杠来转义而不是像常规Regex中那样使用单反斜杠)
  • .+-任何字符,一次或多次

答案 1 :(得分:0)

为了避免验证输入有效载荷,您可以使用以下正则表达式:

  ^ payload \。[^。] + $
 

答案 2 :(得分:0)

输入数组:

val ar = Array("payload.Hello","Hipayload.Hello","payload.H","payload.")

正则表达式字符串:

 val p = """^payload\..{1,}""" 

在Scala REPL中:

scala> val ar = Array("payload.Hello","Hipayload.Hello","payload.H","payload.")
ar: Array[String] = Array(payload.Hello, Hipayload.Hello, payload.H, payload.)

scala> val p = """^payload\..{1,}"""
p: String = ^payload\..{1,}

测试:

scala> ar.map(x=>if(x.matches(p))"Valid" else "InValid")
res3: Array[String] = Array(Valid, InValid, Valid, InValid)