I’m trying to return a prefix of a string, my related question is here,but I’ve run into a new problem.
How to return the string prefix from regexp
Basically I have a strings like
23430-BL 23430BZ 23430BK/BL
The Extensions I’m trying to remove are
strip_ext = BK/BL|BZ|BL
The regular expression I’m using to get the string without the extension is
prefix = sample_data[/(.*[^-])-?(?:#{strip_ext})/,1]
This is returning
23430 23430 23430-BK
In theory, I understand that the regexp finds the BL match, and for some reason selects that as the match over the BK/BL. But is there a way to get the regexp to find BK/BL rather than BL?
Unfortunately, there isn’t always a dash before the part that I am looking to strip.
I added the original strip_ext list as an example, and thought it would make it easy to understand. An actual strip_ext list looks like this and changes based on the sample data provided, so unfortunately it isn’t as easy as Mu’s answer below.
AM/DB|AM/BN|RD/BK|PR/WT|YP/BN|YP/CH|YP/DB|PK/BN|PK/CH|PK/DB|SF/BN|SF/CH|SF/DB|AM/CH|BN/CH|BN/DB|CH/BN|CH/DB|DB/BN|DB/CH|BN/BN|CH/CH|MR/BN|MR/CH|MR/DB|DB/DB|AM/AB|DIC/BN|DIC/CH|DIC/DB|BN|DB|WT|BN/WT|BK|WT/BN|BK/BN|BK/DB|BL/BN|BL/DB|BK/CH|BL/CH|AM|CH|FR|SB|AM/BK|AM/WT|PT/CH|BG/CH|BG/DB|MF/CH|MF/DB|YR/CH|YR/DB|WT/DB|pt/bn
Make the first quantifier ungreedy.
See it here on Regexr
The
?causes the.*?to match as less as possible.