2011-01-12 27 views

回答

18
reReplace(string, "^0*(.*?)0*$", "$1", "ALL") 

即:

^ = starting with 
0* = the character "0", zero or more times 
() = capture group, referenced later as $1 
.* = any character, zero or more times 
*? = zero or more, but lazy matching; try not to match the next character 
0* = the character "0", zero or more times, this time at the end 
$ = end of the string 
4
<cfset newValue = REReplace(value, "^0+|0+$", "", "ALL")> 
1

我不是一個ColdFusion的專家,但像,更換所有^ 0 + 0 + $的空字符串,例如:

REReplace("000xyz000","^0+|0+$","") 
1

這似乎工作..會檢查你的用例。

<cfset sTest= "0001" /> 
<cfset sTest= "leading zeros? 0001" /> 
<cfset sTest= "leading zeros? 0001.02" /> 
<cfset sTest= "leading zeros? 0001." /> 
<cfset sTest= "leading zeros? 0001.2" /> 

<cfset sResult= reReplace(sTest , "0+([0-9]+(\.[0-9]+)?)" , "\1" , "all") /> 
0

以上根本不起作用,除了布拉德利的回答!

在ColdFusion中,爲了引用捕獲組,您需要\而不是$,例如, \1而不是$1

所以正確答案是:

reReplace(string, "^0*(.*?)0*$", "\1", "ALL") 

即:

^ = starting with 
0* = the character "0", zero or more times 
() = capture group, referenced later as $1 
.* = any character, zero or more times 
*? = zero or more, but lazy matching; try not to match the next character 
0* = the character "0", zero or more times, this time at the end 
$ = end of the string 

和:

\1 reference to capture group 1 (see above, introduced by () 
0

這個職位是很老,但我張貼的情況下,任何人發現它很有用。我發現自己需要多次修剪自定義字符,所以我想分享一下我寫的最近的幫手,如果您覺得它有用,可以使用rereplace修剪任何自定義字符。它和普通修剪一樣工作,但可以傳遞任何自定義字符串作爲第二參數,它將修剪所有前導/尾隨字符。

/** 
    * Trims leading and trailing characters using rereplace 
    * @param string - string to trim 
    * @param string- custom character to trim 
    * @return string - result 
    */ 
    function $trim(required string, string customChar=" "){ 
     var result = arguments.string; 

     var char = len(arguments.customChar) ? left(arguments.customChar, 1) : ' '; 

     char = reEscape(char); 

     result = REReplace(result, "#char#+$", "", "ALL"); 
     result = REReplace(result, "^#char#+", "", "ALL"); 

     return result; 
    } 

你的情況,你可以使用這個幫手做這樣的事情:

string = "0000foobar0000"; 
string = $trim(string, "0"); 
//string now "foobar" 

希望這可以幫助別人:)

相關問題