10

How can I write a regex in RE2 for "match strings not starting with 4 or 5"?

In PCRE I'd use ^(?!4) but RE2 doesn't support that syntax.

Richard
  • 62,943
  • 126
  • 334
  • 542

2 Answers2

9

You can use this regex:

^[^45]

^ matches start and [^45] matches anything but 4 or 5 at start.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 2
    And if you also want to match the empty string, use `^(?:[^45]|$)`. – Tim Pietzcker Jan 28 '15 at 16:28
  • 1
    Yes that's right, thanks for adding this important addendum @TimPietzcker – anubhava Jan 28 '15 at 16:30
  • similar to this how to omit the word when it contains `-ed` in it? any idea for this [link](https://regex101.com/r/I5Wsbf/3). Here 2 match cases are working fine, but condition on negate (not matching case) seems to be not working. Pls correct me if i'm wrong. @anubhava – CdVr Jul 25 '20 at 07:31
0

Here's a variant of the solution for strings of words, not individual characters.

The way I do it is to look twice.

First, find all the items that match, then filter them to get the final answer

example

  • test data
    aaabaraaa
    aaafooaaa
    aaazooaaa
    aaaqooaaa
    
    suppose I want to find center text(between "aaa"), and it should not be "bar" or "foo"

it's easy with PCRE1 => https://regex101.com/r/nJcbt1/1/

use re2 I will choose divide and conquer: To a reduced scope with the group, and then filter.

a solution writing with Golang => Go Playground


[1] PCRE: Perl Compatible Regular Expressions

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Carson
  • 6,105
  • 2
  • 37
  • 45