Regex: Matching by exclusion, without look-ahead - is it possible?

后端 未结 4 1267
既然无缘
既然无缘 2020-11-28 11:03

In some regex flavors, [negative] zero-width assertions (look-ahead/look-behind) are not supported.

This makes it extremely difficult (impossible?) to state an excl

4条回答
  •  臣服心动
    2020-11-28 11:36

    You can usually look for foo and invert the result of the regex match from the client code.

    For a simple example, let's say you want to validate that a string contains only certain characters.

    You could write that like this:

    ^[A-Za-z0-9.$-]*$

    and accept a true result as valid, or like this:

    [^A-Za-z0-9.$-]

    and accept a false result as valid.

    Of course, this isn't always an option: sometimes you just have to put the expression in a config file or pass it to another program, for example. But it's worth remembering. Your specific problem, for example, the expression is much simpler if you can use negation like this.

提交回复
热议问题