I have a string that I need to change using regex. So tried a lot of different things, and this is how close I came. Below are a few examples of what the string can be and what it that case the result should be:
case A: "Schoenen US 30 / " should become -> "30"
case B: "Dames US 30 / " should become -> "US 30"
case C: "Dames US w30 / " should become -> "US 30"
case D: "Heren US w30 / L34" should become -> "US 30 / 34"
case E: "Dames US L / " should become -> "US L"
So what I need to do is: 1. match the part: "Schoenen US ","Dames " and "Heren " (so including end space). 2. match any "w","W","l" and "L" in the string (need to be removed) 3. match " / " only on the end of string (if it exists)
So what I came up with:
case A: "/\b(Dames[ ]|dames[ ]|Heren[ ]|heren[ ]|Schoenen US[ ]|[WwLl]).([0-9][0-9]).(\/ )/g" with substitution "$2"
case B & C: "/\b(Dames[ ]|dames[ ]|Heren[ ]|heren[ ]|Schoenen US[ ]|[WwLl]| \/ )/g" with empty substitution
case D: "/\b(Dames[ ]|dames[ ]|Heren[ ]|heren[ ]|Schoenen US[ ]|[WwLl])/g" with empty substitution
case E: No idea how to do this
These regular expressions do what I want (except for the case E ofcourse). But the problem is that I can only use one regex, so I somehow need to combine all 4 of them. I am a complete beginner when it comes to regex, so if anyone can point me in the right direction would be awesome.
Try to merge all cases to single pattern as close as possible
function tr(str) {
return str.replace(/(?:Schoenen US |\w+ (US ))(?:[wW]?(\d+ \/ )[lL]?(\d+)|[wW]?(\d+) \/ |([lL]) \/)\s*$/, "$1$2$3$4$5");
}
console.log(tr("Schoenen US 30 / ")); // 30
console.log(tr("Dames US 30 / ")); // US 30;
console.log(tr("Dames US w30 / ")); //US 30
console.log(tr("Heren es US w30 / L34")); // US 30 / 34
console.log(tr("Dames US L / ")); // US L
Hope this will help you to understand regex