-6

自分のニーズに合った正規表現を見つけるために少し助けが必要です。必要なのは、入力が任意の文字列であってもよいことです。正規表現はすべての整数値を見つけて、それらを返します。

string s1 = "This is some string"
string s2 = " this is 2 string"
string s3 = " this is 03 string"
string s4 = "4 this is the 4th string"
string s5 = "some random string: sakdflajdf;la  989230"
string s6 = "3494309 !@# 234234"

今私が欲しいのは正規表現が戻ることです、

for s1 = return null (// nothing)
s2 = return 2
s3 = return 0 and 3 (// may separately as 0 and 3 or together as 03 doesn't matter)
s4 = return 4 and 4 (// it has 4 2 times right?)
s5 = 989230 (// may together as this or separately as 9 8 9 2 3 0 again is unimportant, but what's important is that it should return all integer values)
s6 = 3494309 and 234234 (// again may they be together as this or like this 3 4 9 4 3 0 9 and 2 3 4 2 3 4 that is unimportant, all that is imp is that it should return all integers)

[0-9]、、\dを試し^.*[0-9]+.*$ましたが、どれも機能していないようです。誰か助けてもらえますか?

ps:正規表現を使用してファイルの名前を変更するで更新された質問を参照してください

4

2 に答える 2

9

1つ以上の数字に連続して一致する正規表現は次のとおりです。

\d+

あなたはそれをこのように適用することができます:

Regex.Matches(myString, @"\d+")

オブジェクトのコレクションを返しMatchCollectionます。これには、一致した値が含まれます。

あなたはそれを次のように使うことができます:

var matches = Regex.Matches(myString, @"\d+");

if (matches.Count == 0)
  return null;

var nums = new List<int>();
foreach(var match in matches)
{
  nums.Add(int.Parse(match.Value));
}

return nums;
于 2012-04-11T20:02:21.200 に答える
2

私はそれが少し簡単に見えることを知っていますが、私は\dあなたが望むことをするだろうと思います

あなたがこれを試したと言ったことは知っています...注意すべきことの1つは、これを示すために文字列を使用している場合は、エスケープを無視する必要があるということです

var pattern = @"\d+";
于 2012-04-11T20:03:42.100 に答える