2011-01-12 44 views
3

rereplaceを使用して先行ゼロと後続ゼロをトリミングするにはどうすればよいですか?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番目のパラメータとして「すべて」が必要だと思います。 –

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

上記のコードは、bradleyの回答以外はまったく機能しません。

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を使って任意のカスタム文字をトリミングするように書いてみたいと思っています。これは通常のトリムのように機能しますが、カスタム文字列を2番目のパラメータとして渡すことができ、すべての先頭/末尾の文字がトリミングされます。あなたのケースでは

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

希望これは助けを誰か:)