kelly
kelly

Reputation: 243

regex to match two words with dynamic word in between them in a string

I have a input string like given below and this string can be with spaces and without spaces as well.

Secondly, 666666 is dynamic string which is present in between 80000123456 and SYDNEY BAKERS and it could be any other string as well. Its dynamic.

Input string

ABCD DEF++80000123456 666666 SYDNEY BAKERS 0000000 22222 333333

I want to create an regex which could match my string holding values 80000123456 and SYDNEY BAKERS. And this info could be located at any point of string. Start, end or inbetween ..anywhere.

I have tried this

/^.*?\b80000123456\b.*?\bSYDNEY BAKERS\b.*?$/m

But in this its matches like string 80000123456 and SYDNEY BAKERS could be present independtly at anywhere at the string. But In my case

Pattern could be like this only

80000123456 666666(dynamic) SYDNEY BAKERS

80000123456666666(dynamic)SYDNEY BAKERS

There must be an string in between 80000123456 and SYDNEY BAKERS

Hope its explained ...

Any suggestion on this please ?

Upvotes: 0

Views: 1809

Answers (2)

Sebastien Dufresne
Sebastien Dufresne

Reputation: 765

This could work:

80000123456\s?(\d+?)\s?SYDNEY BAKERS

It does assume that the variable string will be numeric, which you might have to take into consideration.

Advantages:

  • The captured expression is non-greedy
  • Won't get the "spaces" in your captured section

More options:

If you need more than numeric characters, instead of \d+?

  • \w+? match alpha-numeric and a bit more
  • .+? any characters

Here's an example

Upvotes: 0

baao
baao

Reputation: 73241

I hope I understand it correctly as it seems a bit trivial compared to your regex, but

/80000123456(.*)SYDNEY BAKERS/

matches everything in between the values you specified.

DEMO HERE

Upvotes: 1

Related Questions