Scala Regex启用多行选项 [英] Scala Regex enable Multiline option

查看:90
本文介绍了Scala Regex启用多行选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Scala,所以这可能有点菜鸟味.

I'm learning Scala, so this is probably pretty noob-irific.

我想要一个多行正则表达式.

I want to have a multiline regular expression.

在Ruby中将是:

MY_REGEX = /com:Node/m

我的Scala看起来像:

My Scala looks like:

val ScriptNode =  new Regex("""<com:Node>""")

这是我的匹配功能:

def matchNode( value : String ) : Boolean = value match 
{
    case ScriptNode() => System.out.println( "found" + value ); true
    case _ => System.out.println("not found: " + value ) ; false
}

我这样称呼它:

matchNode( "<root>\n<com:Node>\n</root>" ) // doesn't work
matchNode( "<com:Node>" ) // works

我尝试过:

val ScriptNode =  new Regex("""<com:Node>?m""")

我真的很想避免不得不使用java.util.regex.Pattern.任何提示都将不胜感激.

And I'd really like to avoid having to use java.util.regex.Pattern. Any tips greatly appreciated.

推荐答案

当首次使用Scala Regex时,这是一个非常常见的问题.

This is a very common problem when first using Scala Regex.

在Scala中使用模式匹配时,它会尝试匹配整个字符串,就好像您使用的是"^"和"$"一样(并且未激活多行分析,后者将\ n匹配到^和$)

When you use pattern matching in Scala, it tries to match the whole string, as if you were using "^" and "$" (and did not activate multi-line parsing, which matches \n to ^ and $).

您想要做的事情将是以下之一:

The way to do what you want would be one of the following:

def matchNode( value : String ) : Boolean = 
  (ScriptNode findFirstIn value) match {    
    case Some(v) => println( "found" + v ); true    
    case None => println("not found: " + value ) ; false
  }

会发现在值内找到ScriptNode的第一个实例,并将那个实例返回为v(如果需要整个字符串,只需打印值).否则:

Which would find find the first instance of ScriptNode inside value, and return that instance as v (if you want the whole string, just print value). Or else:

val ScriptNode =  new Regex("""(?s).*<com:Node>.*""")
def matchNode( value : String ) : Boolean = 
  value match {    
    case ScriptNode() => println( "found" + value ); true    
    case _ => println("not found: " + value ) ; false
  }

将打印所有所有值.在此示例中,(?s)激活dotall匹配(即,将."匹配到新行),并且搜索模式之前和之后的.*确保其将匹配任何字符串.如果要像第一个示例一样使用"v",则可以执行以下操作:

Which would print all all value. In this example, (?s) activates dotall matching (ie, matching "." to new lines), and the .* before and after the searched-for pattern ensures it will match any string. If you wanted "v" as in the first example, you could do this:

val ScriptNode =  new Regex("""(?s).*(<com:Node>).*""")
def matchNode( value : String ) : Boolean = 
  value match {    
    case ScriptNode(v) => println( "found" + v ); true    
    case _ => println("not found: " + value ) ; false
  }

这篇关于Scala Regex启用多行选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆