ColdFusion和尾随逗号

时间:2008-10-08 12:21:25

标签: coldfusion

如何从ColdFusion中的字符串中删除尾随逗号?

6 个答案:

答案 0 :(得分:23)

删除尾随逗号(如果存在):

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

删除一个或多个尾随逗号:

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

答案 1 :(得分:15)

也很简单:

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

说明:这利用了CF列表函数忽略空元素的事实。 ListChangeDelims()因此剥去了最后一个“元素”。

答案 2 :(得分:5)

检查最右边的字符 - 如果是逗号,请将字符串设置为原始字符串,长度为-1。

修剪字符串可确保尾随逗号后的空格不会干扰此方法。

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

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

答案 3 :(得分:4)

这可能比Regex的列表更受欢迎,但有时当我最终过滤/修复脏数据时,我将其转换为数组,然后将其转换回列表。


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

这是作弊,但它有效; - )

答案 4 :(得分:2)

加入Patrick的回答。要在最后替换一个或多个逗号,请使用以下命令: reReplace(myString,“,+ $”,“”,“all”)

以下示例

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

答案 5 :(得分:1)

从“双方”,“右侧”或“左侧”中删除“,”

<cfset theFunnyList = ",!@2ed32,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>

排序列表(数字到A-Z)ASCending

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