Home > Mobile >  How to use RegExp grouping in javascript to parse strings
How to use RegExp grouping in javascript to parse strings

Time:11-05

I need to create a RegExp that will allow me to use groups to properly parse a string for some comparison logic.

consider the following list of strings:

const testSet: string[] = [
    "alpha-4181a",
    "alpha-4181a-2",
    "alpha-4181a_3",
    "example",
    "smokeTest"
]

Note the -2 and _3 which are valid methods of versioning in this naming convention. We wish to maintain support for such.

If we loop through the above set, I am expecting the entire string, WITHOUT versioning if it exists (as shown below)...

const returnSet: string[] = [
"alpha-4181a",
"alpha-4181a",
"alpha-4181a",
"example",
"smokeTest"
]

so far I have the following regex /([-_]\d?)$/gi which does properly identify the versioning at the end of the string. From here, I would like to create an additional group that matches everything that is NOT the versioning convention, but I can't seem to figure it out...

CodePudding user response:

You just need to match everything before the versioning at the end. But you also need lazy matching, which is what ? - see this question for more.

const testSet = [
    "alpha-4181a",
    "alpha-4181a-2",
    "alpha-4181a_3",
    "example",
    "smokeTest"
];

const resultSet = testSet.map((x) => x.match(/^(. ?)(?:[_-]\d)?$/)?.[1] ?? x);
//                                                  ^^^^^^^^^^ versioning here
//                                             ^^^^^ match everything before
console.log(resultSet);

  • Related