Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

regex not returning 2 separate matches as it should

Trying to capture both sentences as separate groups. The regex currently only captures the first sentence only.

string =

Mazda67 vehicle J8473 operated with R/H Nose tire missing Tang Washer
following replacement of wheel assembly by dealership maintenance
personnel.During an inspection at Ford, maintenance personnel found
the tang washer missing and replaced R/H engine mount.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

regex =

(?:^|\.|;)([^.]*missing.*?)(?:\.|$)

Currently returns this only:

Mazda67 vehicle J8473 operated with R/H Nose tire missing Tang Washer
following replacement of wheel assembly by dealership maintenance
personnel.

Desired output:

Match 1:

Mazda67 vehicle J8473 operated with R/H Nose tire missing Tang Washer
following replacement of wheel assembly by dealership maintenance
personnel.

Match2:

During an inspection at Ford, maintenance personnel found the tang
washer missing and replaced R/H engine mount.

I’m using the regex tester here to test: https://regex101.com/

>Solution :

Instead of matching, you can use a lookbehind assertion to not consume the last dot at the end of the string in the first match, that you also want to match in the beginning of the second string.

(?:(?<=[;.])|(?<=^))[^.]*missing[^.]*(?:\.|$)

The pattern matches:

  • (?:(?<=[;.])|(?<=^)) Assert either ; or . or the start of the string
  • [^.]*missing[^.]* Match missing between optional chars other than a dot
  • (?:\.|$) Match either . or assert the end of the string

Regex demo

Note that there is a shorter way of writing the alternation in the comments by @sln, just using ^ instead of (?<=^) as the anchor also does not match a character.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading