问题
I'm attempting to validate a basic form element using Angular 2 Form Validators, and the RegEx I'm placing in to Validators.pattern()
to match a valid URL is matching patterns that theoretically aren't valid when the argument is a String data type.
// example.component.ts
this.exampleForm = fb.group({
// The patterns below will match most URL structures, and are exactly the same
const reg = '^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$';
const patt = new RegExp(/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/);
'url': ['', [
Validators.required,
// Matches many unintended patterns
Validators.pattern(reg),
// Works as intended
Validators.pattern(patt)
]
]
});
The above RegEx pattern, when placed in to a RegEx101.com (example here) targeting the JavaScript RegEx engine, will not match with the string 'goog'. But, in the template for the example.component.ts
class, the pattern does match with a string like 'goog' when the first Validator.pattern(String)
is used. I have also had coworkers mention other patterns behaving strangely when inserted as a string, even though the method description in VS Code accepts a String or RegExp class. Why is this?
回答1:
You may use
const reg = '(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?';
The ^
(at the start) and $
(at the end) will be added by Angular2 automatically (note that you are in charge of properly grouping the pattern in that case, though in this case it is not required).
The most important part here is that you need to double the escaping backslash in the string literal to define a literal backslash that escapes special regex metacharacters.
Also, you do not need to escape /
in a regex constructor notation.
Also, you have ([\/\w \.-]*)*
that is a very poor pattern: it is the same as [/\\w .-]*
, so remove the quantified grouping here.
来源:https://stackoverflow.com/questions/41768721/regex-in-angular-2-form-validators-producing-different-results-when-argument-is