In Scala, data validation and adding constraints to its usage is important for data processing. And checking if a regular expression is present in a string.
在Scala中,数据验证和对其使用增加约束对数据处理很重要。 并检查字符串中是否存在正则表达式。
To check whether the strings contain a regular expression or regex we will use the findFirstIn() method.
为了检查字符串是否包含正则表达式或正则表达式,我们将使用findFirstIn()方法。
Syntax:
句法:
regex.findfirstIn(string)
The method accepts the string in which regex is searched and returns an Option[String] value.
该方法接受在其中搜索正则表达式的字符串 ,并返回Option [String]值。
程序检查字符串是否包含正则表达式 (Program to check if a string contains a regular expression)
object myObject {
def main(args: Array[String]) {
val bike = "harley davidson Iron 883"
val numRegex = "[0-9]+".r
println("String: "+bike)
val matchPattern = numRegex.findFirstIn(bike)
print("Pattern found "+matchPattern)
}
}
Output
输出量
String: harley davidson Iron 883
Pattern found Some(883)
Explanation:
说明:
In this program, we have a string with is to be checked for regular expression which is created using the .r method. The method findFirstIn() is used to check for the presence of the pattern in the string which returns a none if no match is found and the matched string if a match is found.
在此程序中,我们将使用.r方法创建一个字符串,用于检查正则表达式。 方法findFirstIn()用于检查字符串中是否存在模式,如果未找到匹配项,则返回none;如果找到匹配项,则返回匹配的字符串。