如何使用rereplace修剪前导零和尾随零?
它与插入符号,星号和美元符号有关。
一个0。
答案 0 :(得分: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
答案 1 :(得分:4)
<cfset newValue = REReplace(value, "^0+|0+$", "", "ALL")>
答案 2 :(得分:1)
我不是一个冷血专家,但是,用空字符串替换所有^ 0 +和0 + $,例如:
REReplace("000xyz000","^0+|0+$","")
答案 3 :(得分: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" ) />
答案 4 :(得分: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 ( )
答案 5 :(得分: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"
希望这有助于某人:)