2016-01-27 31 views
1

我想在我的頁面的textarea中控制用戶輸入的形式。 輸入具有完全一樣的:Angular ng-pattern:textarea格式正則表達式

enter image description here

這意味着只有三個在第一和第二和之間的第二和第三值之間的一個行和分號值。

現在我使用這個正則表達式來驗證它:

^((([^;]+);([^;]*);([^;]+))\n?)*$ 

它不工作100%,因爲它證明了像

value1;value2;value3 
value1 

爲有效輸入。問題是新行和下一個值1的開始。好像直到在value1之後寫入第一個分號,value1仍然被追加到前一行的value3的末尾。我應該如何改變正則表達式來禁用它,並將每個新的不完整行標記爲無效?

我創建了一個JS小提琴證明: https://jsfiddle.net/tw2y5omc/3/

回答

1

以下的正則表達式:

^((?:[^;]+;){2}(?:[^;\n\r]+))$ 
# captures everything into a group 
# matches everything except a semicolon, followed by a semicolon two times 
# afterwards everything except a semicolon or newlines being bound to the end of the string 

如果你想也允許空值,改爲使用星:

^((?:[^;]*;){2}(?:[^;\n\r]*))$ 

演示on regex101.com

+0

還是一樣的過程。這種輸入應該是無效的:https://regex101.com/r/xS6iC0/4 – witcher

+0

@witcher:更新:https://regex101.com/r/xS6iC0/5 – Jan

+0

謝謝。我只將{2}更改爲(?:[^;] *;),因爲中間值是可選的。 – witcher