簡體   English   中英

正則表達式以驗證逗號分隔的字符串

[英]regex to verify comma separated string

我有以下格式的字符串:名稱,藝術家,詳細信息,類型,長度

逗號之間可以輸入任何字符。 我到目前為止已經做到了,但似乎沒有用:

if(!Regex.IsMatch(songDetails,@"^([\w]+,)+[\w]+$"))
{
 throw new Exception("Enter data into all cells");
}

songDetails是用戶輸入的要驗證的字符串輸入。

我在哪里錯呢?

編輯:我應該更具體地說明該字符串的來源。 我正在從dataGridView讀取值。 如果用戶將該行留空但輸入了一個長度值,則數據將被保存,但不允許這樣做

檢查拆分結果的長度可能比使用正則表達式更簡單。

var songDetailsArray = songDetails.Split(",");

if(songDetailsArray.Length != 5)
{
     throw new Exception("Enter data into all cells");
}

嘗試卸下支架:

if(!Regex.IsMatch(songDetails,@"^(\w+,)+\w+$"))
{
  throw new Exception("Enter data into all cells");
}

\\ w已經是一個字符類。 如果也允許使用空格,請嘗試以下操作:

if(!Regex.IsMatch(songDetails,@"^((\w|\s)+,)+(\w|\s)+$"))
{
  throw new Exception("Enter data into all cells");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM