2011-01-12 4 views
3

rereplace를 사용하여 선행 0과 후행 제로를 자르는 방법은 무엇입니까?ColdFusion의 정규 표현식

캐럿과 별표 및 달러 기호와 관련이 있습니다.

그리고 0

가 여기에 컨닝 페이퍼의 : http://www.petefreitag.com/cheatsheets/regex/

+0

또는 내가 별표 말을해야? –

+7

이것은 속임수입니까? 왜 치트 시트를 쓰지 그래? –

+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

upboated 설명을 포함하는 뛰어난 결정. – scrittler

+0

대체 문자열의 $는 \이어야합니다 (Railo 4.1.2.005에서 테스트 됨) – gogowitsch

4
<cfset newValue = REReplace(value, "^0+|0+$", "", "ALL")> 
1

내가 ColdFusion에서 전문가,하지만 뭔가 같은 대체하지하고 모든^0 + 0 빈 문자열로 + $, 예 :

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

후행 0을 얻지 못했습니다. –

+1

흠, 여기에서 작동합니다 : http://rubular.com/ (테스트를위한 아주 좋은 페이지) – morja

+0

그건 멋진 링크입니다, morja. REReplace에서 3 번째 매개 변수로 "all"이 필요하다고 생각합니다. –

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

이 게시물이 아주 오래하지만 경우에 사람이 발견에 내가 게시하도록하겠습니다 유용합니다. 나는 여러 가지 경우에 사용자 정의 문자를 다듬을 필요가 있음을 알았습니다. 최근 유용한 도우미를 공유하고 싶습니다. 유용하다고 생각되면 다시 배치를 사용하여 사용자 정의 문자를 자르려고했습니다. 일반 트림과 마찬가지로 작동하지만 사용자 정의 문자열을 두 번째 매개 변수로 전달할 수 있으며 모든 앞/뒤 문자를 잘라냅니다. 귀하의 경우에는

/** 
    * 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" 

희망이 도움이 누군가 :)