Skip to content Skip to sidebar Skip to footer

Regex Split String Of Numbers At Finding Of Alpha Characters

OK Regex is one of the most confusing things to me. I'm trying to do this in Javascript. I have a search field that the user will enter a series of characters. Codes are either: 99

Solution 1:

You could use the regex /\d$/ to determine if it ends with a decimal.

\d matches a decimal character, and $ matches the end of the string. The / characters enclose the expression.

Try running this in your javascript console, line by line.

var values = ['999MC111', '999MC', '999XYZ111']; // some test values

// does it end in digits?

!!values[0].match(/\d$/); // evaluates to true
!!values[1].match(/\d$/); // evaluates to false

Solution 2:

To specify the exact number of tokens you must use brackets {}, so if you know that there are 2 alphabetic tokens you put {2}, if you know that there could be 0-4 digits you put {0,4}

^([0-9]{0,4})([a-zA-z]{2})([0-9]{0,4})$

The above RegEx evaluates as follows:

  • 999MC ---> TRUE
  • 999MC111 --> TRUE
  • 999MAC111 ---> FALSE
  • MC ---> TRUE

The splitting of the expression into capturing groups is done by means of grouping subexpressions into parentheses

As you can see in the following link:

http://regexr.com?2vfhv

you obtain this:

3 capturing groups:
group 1: ([0-9]{0,4})
group 2: ([a-zA-z]{2})
group 3: ([0-9]{0,4})


Solution 3:

The regex /^\d{1,4}[a-zA-Z]{2}\d{0,4}$/ matches a series of 1-4 digits, followed by a series of 2 alpha characters, followed by another series of 0-4 digits.

This regex: /^\d{1,4}[a-zA-Z]{2}$/ matches a series of 1-4 digits, followed only by 2 alpha characters.


Solution 4:

Ok so I didnt really care about the middle 2 characters....all that really mattered was the 1st set of numbers and last set of numbers (if any).

So essentially I just needed to deal with digits. So I did this:

var lead = '123mc444'; //For example purposes
var regex = /(\d+)/g;
var result = (lead.match(regex));

var memID = result[0]; //First set of numbers is member id
if(result[1] != undefined) {
    var leadID = result[1];
}

Post a Comment for "Regex Split String Of Numbers At Finding Of Alpha Characters"