regex

Regex - non capturing group


I currently have the following regex:

Regex101: https://regex101.com/r/OIkya1/2

iPhone\s*(SE(?:.*?)\d)|(\d+)|(X)|(SE)

for the test string

iPhone 6S Plus
iPhone SE
iPhone 7
iPhone 8 Plus
iPhone X
iPhone XS
iPhone 11 Pro Max
iPhone 12 Mini
iPhone 13 Pro Max
iPhone SE
iPhone SE2
iPhone SE3
iPhone SE (1st Generation)
iPhone SE (2nd Generation)
iPhone SE (3rd Generation)

My goal is to extract all the identifiers.

iPhone 6S Plus              => 6
iPhone SE                   => SE
iPhone 7                    => 7
iPhone 8 Plus               => 8
iPhone X                    => X
iPhone XS                   => X
iPhone 11 Pro Max           => 11
iPhone 12 Mini              => 12
iPhone 13 Pro Max           => 13
iPhone SE                   => SE
iPhone SE2                  => SE2
iPhone SE3                  => SE3
iPhone SE (1st Generation)  => SE1
iPhone SE (2nd Generation)  => SE2
iPhone SE (3rd Generation)  => SE3

The thing where my regex lacks is the SE1/2/3 recognition as i have to ignore the ' (' while capturing. It would be great if the identifier result would always be captured in group 1.


Solution

  • Try matching:

    iPhone\s*(X|\S+)(?:(?<=SE)\s*\((\d+))?
    

    and list results with:

    $1$2
    

    See: regex101

    Explanation

    MATCH:

    The result will now be a concatenation of groups 1 and 2.