2016-08-17 82 views
1

我是coldfusion的新手,我的目標是根據某些單詞刪除部分字符串。如何使用coldfusion從字符串中刪除單詞或字符

例如:

<cfset myVar = "One of the myths associated with the Great Wall of China is that it is the only man-made structure"/>¨ 

如何刪除單詞「一個與相關的神話」,以 有
中國的長城是,它是唯一的人造結構作爲字符串?

我用下面的函數

RemoveChars(string, start, count) 

但我需要也許創建一個函數與正則表達式或本地的ColdFusion功能。

回答

0

您可以將句子看作是由空格分隔的列表。所以,如果你想切斷你的句子開始與「中國長城」,你可以嘗試

<cfloop list="#myVar#" index="word" delimiters=" "> 
    <cfif word neq "Great"> 
    <cfset myVar = listRest(#myVar#," ")> 
    <cfelse> 
    <cfbreak> 
    </cfif> 
</cfloop> 
<cfoutput>#myVar#</cfoutput> 

有可能做到這一點更快的方法。這是cfLib.org的一個函數,它可以用類似的方式改變列表:LINK

4

我看到這個問題已經有一個公認的答案,但我想我會添加另一個答案:)

您可以通過找到單詞「大」是字符串中做到這一點。使用現代CFML,你可以這樣做:

<cfscript> 
myVar = "One of the myths associated with the Great Wall of China is that it is the only man-made structure"; 

// where is the word 'Great'? 
a = myVar.FindNoCase("Great"); 

substring = myVar.removeChars(1, a-1); 
writeDump(substring); 
</cfscript> 

如果你想切斷兩端的字符,使用mid會給你更多的靈活性。

<cfscript> 
myVar = "One of the myths associated with the Great Wall of China is that it is the only man-made structure"; 

// where is the word 'Great'? 
a = myVar.FindNoCase("Great"); 

// get the substring 
substring = myVar.mid(a, myVar.len()); 
writeDump(substring); 
</cfscript> 

在舊版本的CF將被寫成:

<cfscript> 
myVar = "One of the myths associated with the Great Wall of China is that it is the only man-made structure"; 

// where is the word 'Great' 
a = FindNoCase("Great", myVar); 

// get the substring 
substring = mid(myVar, a, len(myVar)); 
writeDump(substring); 
</cfscript> 

你也可以使用正則表達式來達到同樣的效果,你必須決定哪些是更合適你使用案例:

<cfscript> 
myVar = "One of the myths associated with the Great Wall of China is that it is the only man-made structure"; 

// strip all chars before 'Great' 
substring = myVar.reReplaceNoCase(".+(Great)", "\1"); 

writeDump(substring); 
</cfscript>