Darren
Darren

Reputation: 139

Remove from first dash and beyond

How would I strip everything beyond the first "-pg" using coldfusion regex replace?

http://www.abc.com/Webpage-pg3.html

So in this case the end result would be

http://www.abc.com/Webpage

Upvotes: 0

Views: 731

Answers (6)

Dale Fraser
Dale Fraser

Reputation: 4758

I was going to propose what Jason already proposed

<cfset part = listFirst(urlString, '-') />

If there is a simple option take it.

Upvotes: 0

Mike Causer
Mike Causer

Reputation: 8324

Try this:

<cfscript>
newString = urlString.replaceAll( "-pg.*", "" );
</cfscript>

Syntax:

String.replaceAll( regex, replacement )

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

Or you could skip regex, and use the java String methods, like this one liner for CF9:

<cfscript>
newString = ! urlString.contains( "-pg" ) ? "" : urlString.substring( 0, urlString.indexOf( "-pg" ) );
</cfscript>

The same, without the ternary operator, for older versions of CF:

<cfscript>
if ( urlString.contains( "-pg" ) ) {
    newString = urlString.substring( 0, urlString.indexOf( "-pg" ) );
}
else {
    newString = "";
}
</cfscript>

Ran some benchmarks, it seems the String.replaceAll() method is the fastest on my machine.

<cfscript>
old = "http://www.abc.com/Webpage-pg3.html";

// benchmarks
sys = createObject( "java", "java.lang.System" );

// 35072 ns
// 28160 ns
t1 = sys.nanoTime();
    new1 = old.replaceAll( "-pg.*", "" );
t1 = sys.nanoTime() - t1;

// 20992 ns
// 18176 ns
t2 = sys.nanoTime();
    new2 = old.contains( "-pg" ) ? "" : old.substring( 0, old.indexOf( "-pg" ) );
t2 = sys.nanoTime() - t2;
</cfscript>

Upvotes: 1

ale
ale

Reputation: 6430

I don't know why you're locking yourself into a regex solution. This should work fine:

<cfset stringToCheck = "http://www.abc.com/Webpage-pg3.html">
<cfset stringToFind = "-pg">

<cfset newString = left(stringToCheck,find(stringToFind,stringToCheck)-1)>

Upvotes: 1

FailedDev
FailedDev

Reputation: 26930

Try this:

REReplace("http://www.abc.com/Webpage-pg3.html","(.+)-pg.*","\1")

Pedantic edit:

REReplace("http://www.abc.com/Webpage-pg3.html","(.+?)-pg.*","\1")

Upvotes: 0

Shawn Holmes
Shawn Holmes

Reputation: 3762

<cfset string = "http://www.abc.com/Webpage-pg3.html"  />

<cfset new = ReReplace(string,'(.+?)-pg.*','\1','ONE') />

<cfoutput>#new#</cfoutput>

In this solution, I used a non-greedy match up to the first occurrence of -pg.

Upvotes: -1

Marcus
Marcus

Reputation: 12586

I don't know anything about coldfusion but this regex would match -pg and everything after and store it in the first capturing group:

(-pg.*)

If you then replace it with an empty string you'd get the desired result. You can see it in action here: http://regexr.com?2v965

Upvotes: 1

Related Questions