要件:
- 先行パイプまたは後続パイプをすべて削除します
- 内部用語の周りの「トリム」空白
- 「一度に複数のパイプ」を削除します
そして、これらはいくつかのサンプル入力->出力です:
"|||car | boat|||" -> "car|boat"
"george bush|micheal jordon|bill gates|steve jobs"
-> "george bush|micheal jordon|bill gates|steve jobs"
" george bush|micheal jordon |bill gates |steve jobs "
-> "george bush|micheal jordon|bill gates|steve jobs"
"123|||123" -> "123|123"
そして、ほとんどあなたのために働くあなたの例:
("^\|*(.*?)\|*$")
先に進む前に、次のMSDNリファレンスページに言及することをお勧めします:http://msdn.microsoft.com/en-us/library/az24scfc.aspx
そして、このオンラインテストページ:http ://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
この正規表現はうまくいくかもしれないと思ったので、私の正規表現は十分に強力ではありませんが、それは大変な仕事のように見えます。インラインで文書化しましたが、それでも複雑です(完全に機能しません)
^(?:\|*)((?:\s*)([a-zA-Z0-9]?[a-zA-Z0-9 ]*[a-zA-Z0-9]?)(?:\s*)\|?(?:\|*))(?:\|*)$
^ - start the line/input
(?:\|*) - capture any pipes at the beginning but ignore them
( - begin matching so we can get the values out the other side
(?:\s*) - trim leading spaces
[a-zA-Z0-9]?[a-zA-Z0-9 ]*[a-zA-Z0-9]? - match any alphanumerics with spaces in between
(?:\s*) - trim trailing spaces
\| - match any one pipe
(?:\|*) - ignore any remaining pipes in a row
)* - end matching, we should be done
(?:\|*) - capture any pipes at the end but ignore them
$ - end of the line/input
では、問題を解決してみましょう。
パイプを分割し、先を見越して、次の文字列が空の長さの文字列であるかどうかを確認し、そうでない場合は既存の単語の長さに追加する必要があります。それを試してみましょう:
(この部分ではDotNetPadを使用します)http://dotnetpad.net/ViewPaste/4bpRXD-vZEOwqTLDQbEECg
これは、最小限の手間で必要なことを実行するサンプルアプリです。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DotNetPad {
public static void Main(string[] args) {
string[] tests = new[] {
"|||car | boat|||",
"george bush|micheal jordon|bill gates|steve jobs",
" george bush|micheal jordon |bill gates |steve jobs ",
"123|||123"
};
foreach(var s in tests)
Console.WriteLine(CleanString(s));
}
public static string CleanString(string input) {
string result = string.Empty;
string[] split = input.Split(new[] {
'|'
});
foreach(var s in split) {
if (!string.IsNullOrEmpty(s)) {
result += "|" + s.Trim();
}
}
return result.Substring(1);
}
}
正規表現を機能させるために投稿を編集してから、2番目のコードとそれ以降のすべてに最大10分を費やしました。話の教訓:あなたがしなければならない仕事をするだけで、すべてに正規表現を使う必要はありません。