Regex to extract exact text

Hi,
I’m trying to fetch a value from a string using regex. I’m facing the following issue:
My regex is ^((B)(/){0,1}(A-Z0-9){8})
If My example text looks as follows:
RANDOM TEXT1
BSOMETHI
RAND TEST

Regex is fetching BSOMETHI which is correct

Now if my example text looks as follows:
RANDOM TEXT1
BSOMETHIGH
RAND TEST

Regex is still fetching BSOMETHI which is incorrect

I have the issue with end of the string. If the string length is of 9 or 10 (including /) characters that starts with a B should only be retrieved whereas a string that starts B/ and has more than 10 characters (including /) my regex should not recognize that as a match.

Adding $ at the end of my regex is not working as it recognizes only the last word if I’ve $ at the end but I can have my matching substring anywhere inside a bigger string and it will definitely be separate string.

Adding /s at the end of my regex my output is being added with a garbage value string.trim as well didn’t work because of that.

Following can be the input formats:

  1. RANDOM TEXT1
    BSOMETHI JGYHYU
    RAND TEST

Regex Match: BSOMETHI

  1. RANDOM TEXT1
    HSJGS BSOMETHI GHYHHJ
    RAND TEST

Regex Match: BSOMETHI

3.RANDOM TEXT1
HSJGS B/SOMETHI GHYHHJ
RAND TEST

Regex Match: B/SOMETHI

  1. RANDOM TEXT1
    BSOMETHING
    RAND TEST

Should not fetch any match

Can someone help me in limiting my regex at the end in fetching the correct string

Can you try following regex?

[B][/]{0,1}[A-Z0-9]{8}(\s)

Then you can replace empty charachters with anything :slight_smile:

1 Like

Hi,

How about the following pattern?

\bB/?[A-Z0-9]{7}\b

Regards,

Hi @Yoichi

Can I add \b before ^ as that would be used for looking at the start of a string

If you add ^ to the pattern, the above 2nd and 3rd sample doesn’t match. Is it good for you?
The pattern will be as the following.

 (?m)^B/?[A-Z0-9]{7}\b

Hi,
^((B)(/){0,1}(A-Z0-9){8}) this is currently matching the 2nd and 3rd patterns as well

Hi,

Can you share exact pattern or screenshot? I think it doesn’t match them.

Regards,

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.