如何使用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