Easiest way to REGEX Capture eveything except what you specify?

98 views Asked by At

I for the life of me cannot figure out how to negate everything but what I want to capture with REGEX.

I get close with [^(\d{4}-\d{3}-\d{3}]

But doing a replace in powershell with an input of: 1234-567-899 ABC 1W(23W) BLUE BIKE30 KIT

I get: 1234-567-8991(2330

Instead of 1234-567-899

3

There are 3 answers

1
Liju On

Please try with (?:^\d{4}-\d{3}-\d{3})(.*)$

0
Wiktor Stribiżew On

To match any text after <4-DIGITS>-<3-DIGITS>-<3-DIGITS> pattern at the start of the string, you may use

(?<=^\d{4}-\d{3}-\d{3}).*

See the regex demo. Details:

  • (?<=^\d{4}-\d{3}-\d{3}) - a positive lookbehind that matches a location that is immediately preceded with
    • ^ - start of string
    • \d{4} - four digits
    • - - a hyphen
    • \d{3}-\d{3} - three digits, -, three digits
  • .* - any 0 or more chars other than newline chars, as many as possible
0
Theo On

You could also use regex -replace to remove everything except for the stuff you want to keep.

In your example

"1234-567-899 ABC 1W(23W) BLUE BIKE30 KIT" -replace '^([-\d]+).*', '$1'

would return 1234-567-899