例: targetという名前の文字列で1234を検索したい:
string target = "55555>>><<[1234]<>>>788";
[]、前[、または後]の間の桁数を知らなくても、[、]の間の数字を見つけるにはどうすればよいですか?プロジェクトに小さなコードが必要です。
ありがとう。
例: targetという名前の文字列で1234を検索したい:
string target = "55555>>><<[1234]<>>>788";
[]、前[、または後]の間の桁数を知らなくても、[、]の間の数字を見つけるにはどうすればよいですか?プロジェクトに小さなコードが必要です。
ありがとう。
using System.Text.RegularExpressions;
...
// Declare target
string target = "55555>>><<[1234]<>>>788";
// Declare the regular expression
Regex regex = new Regex(
@"(?<=\[)[0-9]+(?=\])",
RegexOptions.None
);
// Use regex to get value
string number = regex.Match(target).Value;
// Convert to number (optional)
int value = 0;
int.TryParse(number, out value);
// Note: value will be 0 if no matches are found.
この正規表現の機能:
最初のビット(?<=\[)
は「後ろを振り返る」です。ブラケットが数字の前に進むことを保証します。角かっこは正規表現の特殊文字であるため、円記号でエスケープする必要があります。
真ん中のビット[0-9]+
は、任意の数字の1つ以上を探します。ゼロ以上が必要な場合は、プラスの代わりにスターを使用できます。[0-9]*
最後のビット(?=\])
は、「後ろを振り返る」と同様の「先を見る」です。再びブラケットはエスケープされます。
The output will be only the numbers without the brackets but only when the numbers are surrounded by brackets.
This sounds like a job for regular expressions
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string str = "55555>>><<[1234]<>>>788";
Regex r = new Regex(@"\[(\d*)\]");
Match match = r.Match(str);
Console.WriteLine(match.Groups[1].Value);
}
}
}
the above code has the following output
1234
Press any key to continue . . .
以下で十分です。
var match = Regex.Match("55555>>><<[1234]<>>>788", ".*\[(.+)\].*");
var value = match.Groups[1].Value; //= "1234"
値が常に数値である必要がある場合は、他の回答のように(.+)
置き換えることができます。(\d+)
.+
任意の文字
\d
は0から9までの任意の数字を意味します。
Here is a regex which does the trick:
Console.WriteLine (Regex.Match("55555>>><<[1234]<>>>788", @"(?:\[)(?<Data>[^\]]+)(?:\])").Groups["Data"].Value);
// 1234 is outputed