Regex to remove starting and ending string
I am working on a small app where I need to remove the starting and ending
tags and I am having a little trouble getting the expression right.Currently I have this bit of code. The issue is on the second output, nothing is displayed.
<cfcontent reset="true"/>
<cfset myStr = '<br> <br> <br> <br> This is a great Test<br> do you like my test? <br><br><br>'>
<开发者_如何学运维;cfoutput>#myStr#</cfoutput>
<cfset myNewString = REReplaceNoCase(myStr, '(^<.*?>+)|(<.*?>+$)', '' ,'ALL')>
<cfoutput>New: #myNewString#</cfoutput>
The following regex worked for me:
(^<[^>]*?>+)|(<[^>]*?>+$)
It removed the first and last tag if that's what you wanted.
However, the +
after the closing angle bracket suggests that you maybe meant to remove all tags at the start or end; although in the current form it would match one or more closing angle brackets. You need to use groups to change that behavior:
(^(<[^>]*?>\s*)+)|((<[^>]*?>\s*)+$)
This removes all tags at the start or end of the string.
First of all sorry : this is not an answer, I can't comment yet, but I've decided to give you my 2 cents anyway. I found your problem intriguing, and looked into it a little bit.
It turns out this :
<cfset multipleMatches = REReplaceNoCase(myStr, '(<.*?>+)', '- Match -' ,'ALL')>
will match tags as expected, but this:
<cfset singleMatche = REReplaceNoCase(myStr, '(<.*?>+$)', '- Match -' ,'ALL')>
will suddenly become super greedy.
It looks like a bug to me, but I'm not sure that regarding regex I am able to distinguish a bug from a sufficiently advanced feature, which is exactly why using negated character classes like Joey did is our best bet to avoid an excess of head scratching.
精彩评论