2014-07-17 86 views
0

我想要一個正則表達式,它不允許空格在逗號之後,但逗號前的空格應該被允許。 逗號也應該是可選的。正則表達式匹配逗號前的空格,但不匹配後

我現在的正則表達式:

^[\w,]+$ 

我試圖在它添加\s也試過^[\w ,]+$但允許使用空格,逗號後的!

這應該是測試用例:

Hello World // true 
Hello, World // false (space after comma) 
Hello,World // true 
Hello,World World // false 

任何幫助,將不勝感激!

+0

「不允許」是大不明確是什麼?你的意思是明確 –

回答

5

下面的正則表達式將不會允許空間逗號後,

^[\w ]+(?:,[^ ]+)?$ 

DEMO

說明:一行

  • ^開始。
  • [\w ]匹配charcter或空格一個或多個單詞。
  • (?:)這被稱爲非捕獲組。該組內的任何內容都不會被捕獲。
  • (?:,[^ ]+)?逗號後跟任何字符而非空格一次或多次。通過在非捕獲組之後添加?,這會告訴正則表達式引擎它將是可選的。
  • $一行結束
+0

完美!請添加一個explination :) – imbondbaby

+0

@imbondbaby Regex101演示解釋了正則表達式。 – RevanProdigalKnight

+0

對不起,沒有附近的PC ...和Regex101希望我在瀏覽他們的網站之前更新我的瀏覽器。 – imbondbaby

1

您可以使用此正則表達式。

^[\w ]+(?:,\S+)?$ 

說明

^   # the beginning of the string 
[\w ]+  # any character of: word characters, ' ' (1 or more times) 
(?:  # group, but do not capture (optional): 
    ,  # ',' 
    \S+  # non-whitespace (all but \n, \r, \t, \f, and " ") (1 or more times) 
)?   # end of grouping 
$   # before an optional \n, and the end of the string 
+0

它需要在逗號之前留出空格,所以你的行爲不起作用。 – RevanProdigalKnight

+0

已編輯並修復 – hwnd

1

我想這取決於你想要做什麼,如果你只是測試的語法錯誤的存在,你可以使用類似。

See this example here >

var patt =/,/g; // or /\s,/g if you want 
var str = 'Hello ,World ,World'; 
var str2 = 'Hello, World, World'; 
console.log(patt.test(str)) // True, there are space before commas 
console.log(patt.test(str2)) // False, the string is OK! 

向前看符號是有用的,但可能很難在不知道基本理解。

Use this site,它的可視化你的正則表達式