如何使用rereplace修剪前導零和尾隨零?ColdFusion中的正則表達式
它與一個插入符號和一個星星和一個美元符號有關。
和0。
這裏有一個備忘單: http://www.petefreitag.com/cheatsheets/regex/
如何使用rereplace修剪前導零和尾隨零?ColdFusion中的正則表達式
它與一個插入符號和一個星星和一個美元符號有關。
和0。
這裏有一個備忘單: http://www.petefreitag.com/cheatsheets/regex/
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
<cfset newValue = REReplace(value, "^0+|0+$", "", "ALL")>
我不是一個ColdFusion的專家,但像,更換所有^ 0 + 0 + $的空字符串,例如:
REReplace("000xyz000","^0+|0+$","")
這似乎工作..會檢查你的用例。
<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") />
以上根本不起作用,除了布拉德利的回答!
在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 ()
這個職位是很老,但我張貼的情況下,任何人發現它很有用。我發現自己需要多次修剪自定義字符,所以我想分享一下我寫的最近的幫手,如果您覺得它有用,可以使用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"
希望這可以幫助別人:)
或者我應該說星號? – 2011-01-12 16:35:53
這是個詭計問題嗎?你爲什麼不使用備忘單? – 2011-01-12 16:41:08
我並不強壯。 – 2011-01-12 17:05:06