2009-03-17 21 views
0

私は ';'を置き換えるpl/sqlコードで作業しています。これは '〜'とコメントされています。デリミタを別のものに置き換えるC#regex

私のようにコードがある場合:

--comment 1 with~ 
select id from t_id; 
--comment 2 with ~ 
select name from t_id; 
/*comment 3 
with ~*/ 

それはC#で正規表現を使用して行うことができます。

--comment 1 with; 
select id from t_id; 
--comment 2 with ; 
select name from t_id; 
/*comment 3 
with ;*/ 

その後、私はのように私の結果テキストがしたいですか?

答えて

4

正規表現:それを使用する

((?:--|/\*)[^~]*)~(\*/)? 

C#コード:

string code = "all that text of yours"; 
Regex regex = new Regex(@"((?:--|/\*)[^~]*)~(\*/)?", RegexOptions.Multiline); 
result = regex.Replace(code, "$1;$2"); 

C#のが、正規表現でテストおよび交換は=テキストとRegexBuddyで動作しません)

注:私は非常に華麗な正規表現の作家ではないので、おそらくより良い書き方になっている可能性があります。しかし、それは動作します。 1行目のコメントであなたのケースを処理します。 -/* */

編集:他の回答にコメントを読むので、^アンカーを削除してください。コメントの新しい行でも開始されません。

編集2:それは少し簡素化することができると考えた。終了$アンカーもなくてもうまく動作することがわかりました。

説明:

// ((?:--|/\*)[^~]*)~(\*/)? 
// 
// Options:^and $ match at line breaks 
// 
// Match the regular expression below and capture its match into backreference number 1 «((?:--|/\*)[^~]*)» 
// Match the regular expression below «(?:--|/\*)» 
//  Match either the regular expression below (attempting the next alternative only if this one fails) «--» 
//   Match the characters “--” literally «--» 
//  Or match regular expression number 2 below (the entire group fails if this one fails to match) «/\*» 
//   Match the character “/” literally «/» 
//   Match the character “*” literally «\*» 
// Match any character that is NOT a “~” «[^~]*» 
//  Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» 
// Match the character “~” literally «~» 
// Match the regular expression below and capture its match into backreference number 2 «(\*/)?» 
// Between zero and one times, as many times as possible, giving back as needed (greedy) «?» 
// Match the character “*” literally «\*» 
// Match the character “/” literally «/» 
1

正規表現は実際には必要ありません。行を繰り返し、 " - "で始まる行を見つけて ";"それらに "〜"を付けてください。

String.StartsWith("--") - Stringのインスタンスの先頭が指定した文字列と一致するかどうかを判断します。

String.Replace(";", "~") - このインスタンス内の指定されたUnicode文字またはStringのすべての出現が、別の指定されたUnicode文字またはStringに置き換えられた新しい文字列を返します。

+0

も、事は私は改行でそれを分割する必要がありますです。 私はあまりにも大きいコードを持っているので、私はしたくない。 また、 select * from gのようなコードでは、 - select文 を置き換えることはできません。コメントで。 – Archie

関連する問題