2016-05-13 19 views
2

從API獲取我的正則表達式,它們通常以^開始並以$結尾(例如^-?[0-9]+$)。只要將正則表達式作爲一個字符串轉換爲ng-pattern,就會產生一個Lexer Error,因爲angular在字符串上添加了默認的^和$。

Angular API reference

  • If the expression evaluates to a RegExp object, then this is used directly.
  • If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in^and $ characters. For instance, "abc" will be converted to new RegExp('^abc$').

很好,那麼,讓我們嘗試正則表達式字符串轉換成正則表達式對象,我想。所以,我想這一點:

json.data.data[i].validateRegex = new RegExp(json.data.data[i].validateRegex, "g"); 

但它導致另一個錯誤:

Error: ngPattern:noregexp 
Expected Regular Expression 
Expected {} to be a RegExp but was {}. 

我怎樣才能讓我的正則表達式與NG模式工作?最好不要從正則表達式中除去^和$。

+0

你可以添加任何小提琴/ plnkr?這將有助於我們回答你的問題。 –

回答

2

將字符串轉換爲正則表達式對象的作品。

但ng模式不應該有{{ }}在裏面。將它從ng-pattern="{{ regexObj }}"更改爲ng-pattern="regexObj"訣竅!

+0

謝謝你回答你的問題。我和你有同樣的問題。 – sg552