RegEX - Find Magnetic Card String for Track 1 and Track 2 substrings

739 Views Asked by At

A Card reader is simply a keyboard input that once a Card is swiped, a string is displayed in any focused text field.

I would like to split the following:

Track 1: which is delimited by a % and a ?

Track 2: which is delimited by a ; and a ?

However not all Cards have both Tracks, some have only the first, and some have only the second.

I'd like to find a RegEx that parses out Track 1 and Track 2 if either exist.

Here are sample Cards swipes which generates these Strings:

%12345?;54321?               (has both Track 1 & Track 2)
%1234678?                    (has only Track 1)
;98765?                      (has only Track 2)
%93857563932746584?;38475?   (has both Track 1 & Track 2)

This is the example I'm building off of:

%([0-9]+)\?) // for first Track
;([0-9]+)\?) // for second Track
1

There are 1 best solutions below

1
Brian On

This regex will match your track groupings:

/(?:%([0-9]+)\?)?(?:;([0-9]+)\?)?/g

(?:            // non-capturing group
    %          // match the % character
    (          // capturing group for the first number
        [0-9]  // match digits; could also use \d
        +      // match 1 or more digits
    )          // close the group
    \?         // match the ? character
)
?              // match 0 or 1 of the non-capturing group
(?:
    ;          // match the ; character
        [0-9]  
        +
    )
    \?
)
?

BTW, I used regexr to figure out the regex patterns here (free site, no affiliation).