重複の可能性:
文字列(C#)内の文字列の出現をどのようにカウントしますか?
複数のサブ文字列とEnter(Enterキーを押すことによる特殊文字)を間に含む文字列があります。
単語間のEnterキーをカウントする正規表現の書き方を教えてください。
ありがとう
重複の可能性:
文字列(C#)内の文字列の出現をどのようにカウントしますか?
複数のサブ文字列とEnter(Enterキーを押すことによる特殊文字)を間に含む文字列があります。
単語間のEnterキーをカウントする正規表現の書き方を教えてください。
ありがとう
使用する改行記号によっては、 just\r
または justに変更する必要がある場合があります\n
。
var numberLineBreaks = Regex.Matches(input, @"\r\n").Count;
正規表現は必要ありません。文字列を数えるだけです。具体的には、Environment.Newline
sを数えているだけです。それを行う方法はたくさんあります。この SO answerでいくつか説明されています。非効率に見えますが、驚くほどうまく機能するものを次に示します。
int count1 = source.Length - source.Replace(Environment.Newline, "").Length;
正規表現である必要がありますか?おそらくもっと簡単な方法があります...たとえば、使用string[] array = String.Split('\n');
して部分文字列の配列を作成し、次のようにしてカウントを取得できますarray.Length;
このコードを使用できます。
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
long a = CountLinesInString("This is an\r\nawesome website.");
Console.WriteLine(a);
long b = CountLinesInStringSlow("This is an awesome\r\nwebsite.\r\nYeah.");
Console.WriteLine(b);
}
static long CountLinesInString(string s)
{
long count = 1;
int start = 0;
while ((start = s.IndexOf('\n', start)) != -1)
{
count++;
start++;
}
return count;
}
static long CountLinesInStringSlow(string s)
{
Regex r = new Regex("\n", RegexOptions.Multiline);
MatchCollection mc = r.Matches(s);
return mc.Count + 1;
}
}
改行を数えるだけでできます:
int start = -1;
int count = 0;
while ((start = text.IndexOf(Environment.NewLine, start + 1)) != -1)
count++;
return count;