Maria Andre
Maria Andre

Reputation: 23

How to find the regex pattern to find there's code and replace it with blank

I have a strings where there's possible code and I want to replace it with blank

Example -

Input = 9eac83a4-80f4-4a2e-b0fe-7a4a9329ff62Manual Handling.pdf

Output I want = Manual Handling.pdf

Input = 14a19827-8f33-4666-a3cc-ea257875f1f7Fire&Evac.pdf

OutPut I want = Fire&Evac.pdf

Input = 67a89d74-57a9-43cc-9576-001f9315d292BLS-1.pdf

OutPut I want = BLS-1.pdf

Input = 7622a004-43b8-4357-8c95-c8a269e6ef7827276e859ef10d-Mango Super.pdf

Output I want = Mango Super.pdf

Input = d5b0f745aa80d9- Calc.png

Output I want = Calc.png

Input = d5b0f745aa80d9980d090- Covid-19-Test.png

Output I want = Covid-19-Test.png

Input = d5b0f745aa80d9980d090-2a004-43b8-4357-8 Covid-19 Vacc.png

Output I want = Covid-19 Vacc.png

How can I do this?

I tried this regex but not working for all of those(above) cases

var str = "9eac83a4-80f4-4a2e-b0fe-7a4a9329ff62Manual Handling.pdf";
var cleanStr = str.replace(/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/g, "");

Can anyone help me with this please?

Upvotes: 0

Views: 47

Answers (2)

MonkeyZeus
MonkeyZeus

Reputation: 20747

This would work:

.*?(?=[A-Z].*$)
  • .*? capture everything loosely
  • (?=[A-Z].*$) - check that ahead of me should be a capital letter followed by anything; do not capture this

const data = `9eac83a4-80f4-4a2e-b0fe-7a4a9329ff62Manual Handling.pdf
14a19827-8f33-4666-a3cc-ea257875f1f7Fire&Evac.pdf
67a89d74-57a9-43cc-9576-001f9315d292BLS-1.pdf
7622a004-43b8-4357-8c95-c8a269e6ef7827276e859ef10d-Mango Super.pdf
d5b0f745aa80d9- Calc.png
d5b0f745aa80d9980d090- Covid-19-Test.png
d5b0f745aa80d9980d090-2a004-43b8-4357-8 Covid-19 Vacc.png`;

const pattern = /.*?(?=[A-Z].*$)/;
data.split(/\n/).forEach(e => console.log(e.replace(pattern, "")));

Upvotes: 1

ggorlen
ggorlen

Reputation: 57145

The simple pattern /[a-f\d-]{14,} */ works for all of your cases:

const data = `9eac83a4-80f4-4a2e-b0fe-7a4a9329ff62Manual Handling.pdf
14a19827-8f33-4666-a3cc-ea257875f1f7Fire&Evac.pdf
67a89d74-57a9-43cc-9576-001f9315d292BLS-1.pdf
7622a004-43b8-4357-8c95-c8a269e6ef7827276e859ef10d-Mango Super.pdf
d5b0f745aa80d9- Calc.png
d5b0f745aa80d9980d090- Covid-19-Test.png
d5b0f745aa80d9980d090-2a004-43b8-4357-8 Covid-19 Vacc.png`;

const pattern = /[a-f\d-]{14,} */;
data.split(/\n/).forEach(e => console.log(e.replace(pattern, "")));

If this is giving false positives on other strings, a clearer specification for the prefix id format(s) seems necessary.

Upvotes: 0

Related Questions