fzefzef zefzef
fzefzef zefzef

Reputation: 29

Find correct regex

I'm trying to find the correct regex for this case:

I need prefix and suffix between version, ? can be everything (letter, number or nothing)

What I have :

static check(version: string) {
    return /-(\d+)\.(\d+)\.(\d+)-$/.test(version);
} 

THanks for your help :)

Upvotes: 0

Views: 84

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

Wouldn't "???-1-" still be the "prefix", there is no way to tell by a simple regex, you will need to capture everything between number, dot, number, etc... until you meet another dash.

Breakdown

There are three groups: the prefix (optional), version, and suffix (also optional).

  1. ([a-z][a-z-]*\-)?
    • Starts with a letter, followed by zero or more letters and dashes, ending with a dash
  2. ([0-9][0-9.]*)
    • Starts with a number, followed by zero or more numbers and dot-literals
  3. (\-[a-z][a-z-]*)?
    • Starts with a dash, followed by a letter and zero or more letters and dashes

Unit tests

const VERSION_PATTERN = /([a-z][a-z-]*\-)?([0-9][0-9.]*)(\-[a-z][a-z-]*)?/i;

const isVersionValid = (version) =>  VERSION_PATTERN.test(version);

const testCases = [
  { version: 'toto-1-1.0-toto', valid : true  },
  { version: 'toto-1-1.0'     , valid : true  },
  { version: '1-1.0-toto'     , valid : true  },
  { version: '1-1.0'          , valid : true  },
  { version: 'toto'           , valid : false },
];

mocha.setup("bdd");
chai.should();

testCases.forEach(testCase => {  
  describe("Validity test", function() {
      it(`"${testCase.version}" is ${testCase.valid ? 'valid' : 'invalid'}`, () => {
          isVersionValid(testCase.version).should.equal(testCase.valid);
      });
  });
});

mocha.run();
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.2.5/mocha.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.2.5/mocha.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.2.0/chai.js"></script>

<div id="mocha"></div>

Upvotes: 1

Related Questions