文字列を削除したいのですが、次の部分だけを残します。
[a-zA-Z]+[_a-zA-Z0-9-]*
文字で始まり、英数字、アンダースコア、ダッシュを含む文字列を出力しようとしています。正規表現または別の関数でこれを行うにはどうすればよいですか?
正規表現の 2 番目の部分はすべて最初の部分にあるため、次のようにすることができます。
String foo = "_-abc.!@#$5o993idl;)"; // your string here.
//First replace removes all the characters you don't want.
foo = Regex.Replace(foo, "[^_a-zA-Z0-9-]", "");
//Second replace removes any characters from the start that aren't allowed there.
foo = Regex.Replace(foo, "^[^a-zA-Z]+", "");
そのため、許可された文字のみに絞り込むことから始めます。次に、先頭に配置できない許可された文字をすべて取り除きます。
もちろん、正規表現がより複雑になると、このソリューションはすぐに崩壊します。
編集済み
var s = Regex.Matches(input_string, "[a-z]+(_*-*[a-z0-9]*)*", RegexOptions.IgnoreCase);
string output_string="";
foreach (Match m in s)
{
output_string = output_string + m;
}
MessageBox.Show(output_string);
コレクションに文字列があると仮定すると、次のようにします。
またはその逆 - 一致する場合は、新しいコレクションに追加します。
文字列がコレクションに含まれていない場合、入力がどのように見えるかについて詳細を追加できますか?
使用するMatchCollection matchColl = Regex.Matches("input string","your regex");
次に使用します。
string [] outStrings = new string[matchColl.Count]; //A string array to contain all required strings
for (int i=0; i < matchColl.Count; i++ )
outStrings[i] = matchColl[i].ToString();
必要なすべての文字列が outStrings に含まれます。お役に立てれば。
正規表現に一致するすべての識別子を引き出したい場合は、次のように実行できます。
var input = " _wontmatch f_oobar0 another_valid ";
var re = new Regex( @"\b[a-zA-Z][_a-zA-Z0-9-]*\b" );
foreach( Match match in re.Matches( input ) )
Console.WriteLine( match.Value );