Reputation: 29
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
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.
There are three groups: the prefix (optional), version, and suffix (also optional).
([a-z][a-z-]*\-)?
([0-9][0-9.]*)
(\-[a-z][a-z-]*)?
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