[英]C# regular expression to get words between 4 to 10 characters
我正在嘗試獲取字符串中的所有單詞,這些單詞的長度至少為4個字符且少於10個字符。 當我使用以下正則表達式時,它只是將整個字符串作為一個單詞返回。 您能否看下面的示例,並告訴我該如何寫此正則表達式?
string result = "Overfishing, erosion and warmer waters are feeding jellyfish blooms in coastal regions worldwide. And they're causing damage"
string[] words = Regex.Split(result, @"[\W]{4,10}");
foreach (string line in words)
{
Console.WriteLine(line);
}
您的代碼無效,因為該模式僅匹配4到10個連續的非單詞字符的序列,該字符不會出現在字符串中。 因此Regex.Split
僅返回包含原始字符串的數組。
嘗試使用以下模式:
\b\w{4,10}\b
例如:
string[] words = Regex.Matches(result, @"\b\w{4,10}\b")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
這將匹配任何4到10個連續單詞字符的序列,並由單詞邊界包圍。
沒有正則表達式,您可以使用String.Split
方法,例如;
string result = "Overfishing, erosion and warmer waters are feeding jellyfish blooms in coastal regions worldwide. And they're causing damage";
var array = result.Split(new string[] {",", ".", " "}, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in array)
{
if(item.Length >= 4 && item.Length < 10)
Console.WriteLine(item);
}
輸出將是;
erosion
warmer
waters
feeding
jellyfish
blooms
coastal
regions
worldwide
they're
causing
damage
這里有demonstration
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.