简体   繁体   中英

scala - regex - match everything except “{{”

I want to match everything including "{", "{{{", and the matching stops when it reaches "{{".

I tried to use the following code, but it would also stop when it reaches "{{{"

"^(.(?![{][{]))+[^{]".r

Is there a way to match everything except "{{"

Your description is vague and imprecise. I don't think this is exactly what you're after but maybe it will help.

val pttrn = """(\{|\{\{\{+)"""

"{" matches pttrn    //true
"{{" matches pttrn   //false
"{{{" matches pttrn  //true
"{{{{" matches pttrn //true

If I understand your requirement correctly, you can enclose {{ with word boundary \\b in your regex pattern:

val pattern = """^(.*?)\b\{\{\b.*$""".r
val str = "{a}bb{{{cc}}}ddd{{e}}ff{{{{gg}}}}"

str match {
  case pattern(s) => s
  case _ => "no-match"
}
// res1: String = {a}bb{{{cc}}}ddd

I came up with this one:

val samples = List ("foo{bar", "foo{{bar", "foo{{{bar", "{foo{bar{{baz{{{fobar{", "{{foo{bar{{baz{{{fobar{{")
samples.map (_.replaceAll ("(^|[^{])\\{{2}([^{]|$)", "##")) 
res62: List[String] = List(foo{bar, fo##ar, foo{{{bar, {foo{ba##az{{{fobar{, ##oo{ba##az{{{foba##)

It replaces the pattern, which shall survive, but I guess you may ask for pattern.matches (...) and if not, delete.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM