'Regex to match very occurrence in string

I have a string "Format: Multiple videos Length:20 mins ....Format: Video with Length: 50 mins" and want to enclose "Format ...mins" part in a tag e.g.

"<p>Format: Multiple videos Length:20 mins</p> ....<p>Format: Video with Length: 50 mins</p>"

The regex I have in Coldfusion is

<cfset str= reReplace(str, "Format:(.*?)Video(.*?)mins", "<p>Format:\1Video\2mins</p>", "ALL")>

but I get output as

"<p>Format: Multiple videos Length:20 mins ....Format: Video with Length: 50 mins</p>"

What is the proper regex to match every occurrence in the string?



Solution 1:[1]

You can use

REReplaceNoCase(str, "Format:((?:(?!Format:|Video|mins).)*)Video((?:(?!Format:|mins).)*)mins", "<p>Format:\1Video\2mins</p>", "ALL")

See the regex demo.

Details:

  • REReplaceNoCase - case insensitive regex replace function
  • Format: - a fixed string
  • ((?:(?!Format:|Video|mins).)*) - Group 1: any text up to the first Video that has no Format:, Video and mins substrings
  • Video - a fixed string
  • ((?:(?!Format:|mins).)*) - Group 2: any text up to the first mins that has no Format: and mins substrings
  • mins - a fixed string

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew