1

文字列を削除したいのですが、次の部分だけを残します。

[a-zA-Z]+[_a-zA-Z0-9-]*

文字で始まり、英数字、アンダースコア、ダッシュを含む文字列を出力しようとしています。正規表現または別の関数でこれを行うにはどうすればよいですか?

4

5 に答える 5

2

正規表現の 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]+", "");

そのため、許可された文字のみに絞り込むことから始めます。次に、先頭に配置できない許可された文字をすべて取り除きます。

もちろん、正規表現がより複雑になると、このソリューションはすぐに崩壊します。

于 2012-06-07T19:55:54.417 に答える
0

編集済み

   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);
于 2012-06-07T19:54:50.407 に答える
0

コレクションに文字列があると仮定すると、次のようにします。

  1. コレクション内の foreach 要素を正規表現と一致させます
  2. !success の場合、コレクションから文字列を削除します

またはその逆 - 一致する場合は、新しいコレクションに追加します。

文字列がコレクションに含まれていない場合、入力がどのように見えるかについて詳細を追加できますか?

于 2012-06-07T19:56:52.157 に答える
0

使用する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 に含まれます。お役に立てれば。

于 2012-06-07T20:10:30.197 に答える
0

正規表現に一致するすべての識別子を引き出したい場合は、次のように実行できます。

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 );
于 2012-06-07T20:00:34.030 に答える