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