Search code examples
regexstringregex-greedy

RegEx for finding strings with chars and numbers


I am trying to match strings that are part numbers mixed with normal text.

Here are a few examples.

  1. Towing Cntrl Ecu,Gl3t-19H378-Ac
  2. Assy,Pwr,Tested Gd,Priv-M50t3
  3. Left,Rear,Brn-Tan,Pwr,4DR,Mju1
  4. T-Case Ecu,56029590AE
  5. Right,Blind Spot Module,284K0 9HS0F

In these examples I am trying to match.

  1. Gl3t-19H378-Ac
  2. Priv-M50t3
  3. Mju1
  4. 56029590AE
  5. 284K0 and 9HS0F

I am in .Net and this is the Regex I have been using.

(\b[a-zA-Z0-9][a-zA-Z0-9\-]{1,32}(\b|$)(?<=[0-9]))

It works for what I need if the match ends in a number. The rule I want is to match any string between word boundaries that is either all numbers or numbers and chars mixed, but never just chars.


Solution

  • This should do it:

    \b[a-zA-Z0-9-]*\d[a-zA-Z0-9-]*\b
    

    If you need to restrict the length to a maximum of 32, add a look ahead:

    \b(?=[a-zA-Z0-9-]{1,32}\b)[a-zA-Z0-9-]*\d[a-zA-Z0-9-]*\b
    

    If the underscore character is OK too, you can use [\w-] instead of [a-zA-Z0-9-].