首页 > 解决方案 > Scala Regex Positive and Negative Look Behind at the same time

问题描述

I have an input string like this

val input = """["abc:def&ghi:jkl"]"""

I want to extract abc and ghi So I wrote this regex which works

val regex = """(?<=["&])(\w+)(?=[:])""".r
regex.findAllIn(input).foreach(println)

So basically I have a look ahead for : and a look behind for either " or &.

So far so good. But now I have an input like this

val input = """["abc:de_&_f:xyz&ghi:jkl"]"""

it matches

abc
_f
ghi

I want to change the logic of my regex to say.

Match a \w+ when look ahead is true for : and look behind is true for & and false for _&_

So I want to use the positive and negative look behind at the same time. How do I do that?

标签: regexscala

解决方案


您可以在正则表达式的后向表达式中添加一个否定的lookbehind和一个否定的lookahead,如下所示:

(?<=(?:(?<!_)&(?!_)|"))\w+(?=:)

正则表达式演示

在这里,我们在后视条件中使用了一个交替,即:

  • (?<!_)&(?!_)|":&前后不匹配则匹配_
  • |: 或者
  • "匹配"

对于您的情况,这个较短的正则表达式也可能有效:

(?<=["&])(?<!_&)\w+(?=:)

正则表达式演示 2

(?<!_&)\w+如果前面有.将跳过匹配项_&


推荐阅读