简体   繁体   中英

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 eg

"<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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM