2008-10-08 104 views

回答

21

要刪除尾隨逗號(如果它存在):

REReplace(list, ",$", "") 

要去除的一個或多個拖尾逗號:

REReplace(list, ",+$", "") 
+0

我首先嚐試了一個普通替換,但是當我這樣做時,它當然會刪除字符串中的所有逗號。我只想刪除那個尾隨的那個。 – 2008-10-08 12:25:43

5

檢查最右邊的char - 如果是逗號,則將字符串設置爲原始的子串,長度爲-1。

修整字符串可確保尾隨逗號後的空格不會干擾此方法。

<cfset myStr = "hello, goodbye,"> 
<cfset myStr = trim(myStr)> 

<cfif right(myStr, 1) is ","> 
    <cfset myStr = left(myStr, len(myStr)-1)> 
</cfif> 
+0

這似乎是伎倆。感謝 – 2008-10-08 12:31:02

+1

在嘗試下面的Patrick's Reg Ex之後,它再次完成了我所需要的更少的代碼,再次感謝。 – 2008-10-08 12:47:29

+0

帕特里克的更好的答案好吧 - 我的更快速的黑客攻擊。很高興它爲你排序任何方式! – ConroyP 2008-10-08 12:54:36

2

要添加到帕特里克答案。爲了在年底更換一個或多個逗號使用以下命令: reReplace(MyString的, 「+ $」, 「」, 「全」)

例子下面

<cfset myString = "This is the string, with training commas,,,"> 
<cfset onlyTheLastTrailingComma = reReplace(myString, ",$", "", "all")> 
<cfset allTrailingCommas = reReplace(myString, ",+$", "", "all")> 
<cfoutput>#onlyTheLastTrailingComma#<br />#allTrailingCommas#</cfoutput> 
4

這可能是更多的性能比Regex的列表要好,但有時當我最終過濾/修復髒數據時,我將它轉換爲數組,然後將其轉換回列表。


<cfset someVariable = arrayToList(listToArray(someVariable, ","), ",")> 

它的欺騙,但它工作;-)

14

也容易:

<cfset CleanList = ListChangeDelims(DirtyList, ",", ",")> 

解釋:這需要一個事實,即CF名單函數忽略空元素的優勢。 ListChangeDelims()因此剝離最後一個「元素」。

1

雙方,只要在右側,或者只是左側刪除「」

<cfset theFunnyList = ",[email protected],a,b,c,d,%442,d,a"> 

更換奇怪的字符,並用逗號分隔

<cfset theList = rereplace(theFunnyList, "[^A-Za-z0-9]+", ",", "all")> 
<cfset theList = trim(theList)> 
<cfif left(theList, 1) is "," and right(theList, 1) is ","> 
    <cfset theList = right(theList, len(theList)-1)> 
    <cfset theList = left(theList, len(theList)-1)> 
<cfelseif right(theList, 1) is ","> 
    <cfset theList = left(theList, len(theList)-1)> 
<cfelseif left(theList, 1) is ","> 
    <cfset theList = right(theList, len(theList)-1)> 
</cfif> 

排序列表(數字到AZ) ASCending

<cfoutput> #ListSort("#theList#", "text", "ASC", ",;")# </cfoutput>