SomeDude
SomeDude

Reputation: 320

What's the JS RegExp for this specific string?

I have a rather isolated situation in an inventory management program where our shelf locations have a specific format, which is always Letter: Number-Letter-Number, such as Y: 1-E-4. Most of us coworkers just type in "y1e4" and are done with it, but that obviously creates issues with inconsistent formats in a database. Are JS RegExp's the ideal way to automatically detect and format these alphanumeric strings? I'm slowly wrapping my head around JavaScript's Perl syntax, but what's a simple example of formatting one of these strings?

Upvotes: 1

Views: 86

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626774

I understand the question as "convert LetterNumberLetterNumber to Letter: Number-Letter-Number.

You may use

/^([a-z])(\d+)([a-z])(\d+)$/i

and replace with $1: $2-$3-$4

Details:

  • ^ - start of string
  • ([a-z]) - Group 1 (referenced with $1 from the replacement pattern) capturing any ASCII letter (as /i makes the pattern case-insensitive)
  • (\d+) - Group 2 capturing 1 or more digits
  • ([a-z]) - Group 3, a letter
  • (\d+) - Group 4, a number (1 or more digits)
  • $ - end of string.

See the regex demo.

var re = /^([a-z])(\d+)([a-z])(\d+)$/i; 
var s = 'y1e2';
var result = s.replace(re, '$1: $2-$3-$4');
console.log(result);

OR - if the letters must be turned to upper case:

var re = /^([a-z])(\d+)([a-z])(\d+)$/i; 
var s = 'y1e2';
var result = s.replace(re, 
   (m,g1,g2,g3,g4)=>`${g1.toUpperCase()}: ${g2}-${g3.toUpperCase()}-${g4}`
);
console.log(result);

Upvotes: 1

Bamieh
Bamieh

Reputation: 10906

spec: detect string format of either "W: D-W-D" or "WDWD" and return "W: D-W-D"

This function will accept any format and return undefined if it doesnt match, returns the formatted string if a match does occur.

function validateInventoryCode(input) {
   var regexp = /^([a-zA-Z]+)(?:\:\s*)?(\d+)-?(\w+)-?(\d+)$/
   var r = regexp.exec(input);
   if(r != null) {
      return `${r[1]}: ${r[2]}-${r[3]}-${r[4]}`;
   }
}

var possibles = ["y1e1", "y:1e1", "Y: 1r3", "y:    32e4", "1:e3e"];

possibles.forEach(function(posssiblity) {
  console.log(`input(${posssiblity}), result(${validateInventoryCode(posssiblity)})`);
})



function validateInventoryCode(input) {
  var regexp = /^([a-zA-Z]+)(?:\:\s*)?(\d+)-?(\w+)-?(\d+)$/
  var r = regexp.exec(input);
  if (r != null) {
    return `${r[1]}: ${r[2]}-${r[3]}-${r[4]}`;
  }
}

Upvotes: 1

Amin Jafari
Amin Jafari

Reputation: 7207

this is the function to match and replace the pattern: DEMO

function findAndFormat(text){

  var splittedText=text.split(' ');

  for(var i=0, textLength=splittedText.length; i<textLength; i++){

    var analyzed=splittedText[i].match(/[A-z]{1}\d{1}[A-z]{1}\d{1}$/);

    if(analyzed){
        var formattedString=analyzed[0][0].toUpperCase()+': '+analyzed[0][1]+'-'+analyzed[0][2].toUpperCase()+'-'+analyzed[0][3];
            text=text.replace(splittedText[i],formattedString);
    }
  }
  return text;
}

Upvotes: 0

rccursach
rccursach

Reputation: 315

i think it's just as it reads: y1e4

Letter, number, letter, number:

/([A-z][0-9][A-z][0-9])/g

And yes, it's ok to use regex in this case, like form validations and stuff like that. it's just there are some cases on which abusing of regular expressions gives you a bad performance (into intensive data processing and the like)

Example

"HelloY1E4world".replace(/([A-z][0-9][A-z][0-9])/g, ' ');

should return: "Hello world"

regxr.com always comes in handy

Upvotes: -1

Related Questions