refactor(RegExpWrapper): remove the facade (#10512)

This commit is contained in:
Jason Choi 2016-08-05 09:50:49 -07:00 committed by Alex Rickabaugh
parent b4613ab2d2
commit 83e2d3d1cb
31 changed files with 112 additions and 194 deletions

View File

@ -9,12 +9,12 @@
import {Pipe, PipeTransform} from '@angular/core';
import {NumberFormatStyle, NumberFormatter} from '../facade/intl';
import {NumberWrapper, RegExpWrapper, Type, isBlank, isNumber, isPresent, isString} from '../facade/lang';
import {NumberWrapper, Type, isBlank, isNumber, isPresent, isString} from '../facade/lang';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
var defaultLocale: string = 'en-US';
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(\-(\d+))?)?$/g;
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(\-(\d+))?)?$/;
function formatNumber(
pipe: Type, value: number | string, style: NumberFormatStyle, digits: string,
@ -36,8 +36,8 @@ function formatNumber(
}
if (isPresent(digits)) {
var parts = RegExpWrapper.firstMatch(_NUMBER_FORMAT_REGEXP, digits);
if (!parts) {
var parts = digits.match(_NUMBER_FORMAT_REGEXP);
if (parts === null) {
throw new Error(`${digits} is not a valid digit info for number pipes`);
}
if (isPresent(parts[1])) { // min integer digits

View File

@ -7,7 +7,7 @@
*/
import {Pipe, PipeTransform} from '@angular/core';
import {RegExpWrapper, StringWrapper, isBlank, isFunction, isNumber, isString} from '../facade/lang';
import {StringWrapper, isBlank, isFunction, isNumber, isString} from '../facade/lang';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
/**
@ -61,7 +61,7 @@ export class ReplacePipe implements PipeTransform {
}
if (isFunction(replacement)) {
const rgxPattern = isString(pattern) ? RegExpWrapper.create(pattern) : pattern;
const rgxPattern = isString(pattern) ? new RegExp(pattern, 'g') : pattern;
return StringWrapper.replaceAllMapped(
input, rgxPattern, <(m: string[]) => string>replacement);

View File

@ -9,7 +9,7 @@
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {ReplacePipe} from '@angular/common';
import {RegExpWrapper, StringJoiner} from '../../src/facade/lang';
import {StringJoiner} from '../../src/facade/lang';
export function main() {
describe('ReplacePipe', () => {
@ -45,9 +45,9 @@ export function main() {
it('should return a new string with the pattern replaced', () => {
var result1 = pipe.transform(str, 'Douglas', 'Hugh');
var result2 = pipe.transform(str, RegExpWrapper.create('a'), '_');
var result2 = pipe.transform(str, /a/g, '_');
var result3 = pipe.transform(str, RegExpWrapper.create('a', 'i'), '_');
var result3 = pipe.transform(str, /a/gi, '_');
var f = ((x: any) => { return 'Adams!'; });

View File

@ -9,7 +9,7 @@
import {ANY_STATE, FILL_STYLE_FLAG} from '../../core_private';
import {CompileAnimationAnimateMetadata, CompileAnimationEntryMetadata, CompileAnimationGroupMetadata, CompileAnimationKeyframesSequenceMetadata, CompileAnimationMetadata, CompileAnimationSequenceMetadata, CompileAnimationStateDeclarationMetadata, CompileAnimationStateTransitionMetadata, CompileAnimationStyleMetadata, CompileAnimationWithStepsMetadata} from '../compile_metadata';
import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {NumberWrapper, RegExpWrapper, isArray, isBlank, isPresent, isString, isStringMap} from '../facade/lang';
import {NumberWrapper, isArray, isBlank, isPresent, isString, isStringMap} from '../facade/lang';
import {Math} from '../facade/math';
import {ParseError} from '../parse_util';
@ -465,13 +465,13 @@ function _fillAnimationAstStartingKeyframes(
function _parseTimeExpression(
exp: string | number, errors: AnimationParseError[]): _AnimationTimings {
var regex = /^([\.\d]+)(m?s)(?:\s+([\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?/gi;
var regex = /^([\.\d]+)(m?s)(?:\s+([\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?/i;
var duration: number;
var delay: number = 0;
var easing: string = null;
if (isString(exp)) {
var matches = RegExpWrapper.firstMatch(regex, <string>exp);
if (!isPresent(matches)) {
const matches = exp.match(regex);
if (matches === null) {
errors.push(new AnimationParseError(`The provided timing value "${exp}" is invalid.`));
return new _AnimationTimings(0, 0, null);
}

View File

@ -11,7 +11,7 @@ import {ChangeDetectionStrategy, SchemaMetadata, ViewEncapsulation} from '@angul
import {LifecycleHooks, reflector} from '../core_private';
import {ListWrapper, StringMapWrapper} from './facade/collection';
import {BaseException, unimplemented} from './facade/exceptions';
import {RegExpWrapper, Type, isBlank, isPresent, isStringMap, normalizeBlank, normalizeBool} from './facade/lang';
import {Type, isBlank, isPresent, isStringMap, normalizeBlank, normalizeBool} from './facade/lang';
import {CssSelector} from './selector';
import {getUrlScheme} from './url_resolver';
@ -23,7 +23,7 @@ import {sanitizeIdentifier, splitAtColon} from './util';
// group 1: "prop" from "[prop]"
// group 2: "event" from "(event)"
// group 3: "@trigger" from "@trigger"
const HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/g;
const HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/;
const UNDEFINED = new Object();
export abstract class CompileMetadataWithIdentifier {
@ -434,8 +434,8 @@ export class CompileDirectiveMetadata implements CompileMetadataWithIdentifier {
var hostAttributes: {[key: string]: string} = {};
if (isPresent(host)) {
StringMapWrapper.forEach(host, (value: string, key: string) => {
var matches = RegExpWrapper.firstMatch(HOST_REG_EXP, key);
if (isBlank(matches)) {
const matches = key.match(HOST_REG_EXP);
if (matches === null) {
hostAttributes[key] = value;
} else if (isPresent(matches[1])) {
hostProperties[matches[1]] = value;

View File

@ -11,7 +11,7 @@ import {Injectable} from '@angular/core';
import * as chars from '../chars';
import {ListWrapper} from '../facade/collection';
import {BaseException} from '../facade/exceptions';
import {RegExpWrapper, StringWrapper, escapeRegExp, isBlank, isPresent} from '../facade/lang';
import {StringWrapper, escapeRegExp, isBlank, isPresent} from '../facade/lang';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../html_parser/interpolation_config';
import {AST, ASTWithSource, AstVisitor, Binary, BindingPipe, Chain, Conditional, EmptyExpr, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, ParseSpan, ParserError, PrefixNot, PropertyRead, PropertyWrite, Quote, SafeMethodCall, SafePropertyRead, TemplateBinding} from './ast';
@ -29,8 +29,8 @@ export class TemplateBindingParseResult {
}
function _createInterpolateRegExp(config: InterpolationConfig): RegExp {
const regexp = escapeRegExp(config.start) + '([\\s\\S]*?)' + escapeRegExp(config.end);
return RegExpWrapper.create(regexp, 'g');
const pattern = escapeRegExp(config.start) + '([\\s\\S]*?)' + escapeRegExp(config.end);
return new RegExp(pattern, 'g');
}
@Injectable()

View File

@ -8,7 +8,7 @@
import {BaseException} from '@angular/core';
import {RegExpWrapper, StringWrapper, evalExpression, isBlank, isPresent, isString} from '../facade/lang';
import {StringWrapper, evalExpression, isBlank, isPresent, isString} from '../facade/lang';
import {EmitterVisitorContext, OutputEmitter} from './abstract_emitter';
import {AbstractJsEmitterVisitor} from './abstract_js_emitter';

View File

@ -9,11 +9,11 @@
import {Injectable} from '@angular/core';
import {BaseException} from '../facade/exceptions';
import {Math, RegExpWrapper, isBlank, isPresent} from '../facade/lang';
import {Math, isBlank, isPresent} from '../facade/lang';
// asset:<package-name>/<realm>/<path-to-module>
var _ASSET_URL_RE = /asset:([^\/]+)\/([^\/]+)\/(.+)/g;
var _ASSET_URL_RE = /asset:([^\/]+)\/([^\/]+)\/(.+)/;
/**
* Interface that defines how import statements should be generated.
@ -26,8 +26,8 @@ export abstract class ImportGenerator {
export class AssetUrl {
static parse(url: string, allowNonMatching: boolean = true): AssetUrl {
var match = RegExpWrapper.firstMatch(_ASSET_URL_RE, url);
if (isPresent(match)) {
const match = url.match(_ASSET_URL_RE);
if (match !== null) {
return new AssetUrl(match[1], match[2], match[3]);
}
if (allowNonMatching) {

View File

@ -8,17 +8,18 @@
import {ListWrapper} from './facade/collection';
import {BaseException} from './facade/exceptions';
import {RegExpMatcherWrapper, RegExpWrapper, StringWrapper, isBlank, isPresent} from './facade/lang';
import {StringWrapper, isBlank, isPresent} from './facade/lang';
const _EMPTY_ATTR_VALUE = '';
const _SELECTOR_REGEXP = RegExpWrapper.create(
'(\\:not\\()|' + //":not("
'([-\\w]+)|' + // "tag"
'(?:\\.([-\\w]+))|' + // ".class"
'(?:\\[([-\\w*]+)(?:=([^\\]]*))?\\])|' + // "[name]", "[name=value]" or "[name*=value]"
'(\\))|' + // ")"
'(\\s*,\\s*)'); // ","
const _SELECTOR_REGEXP = new RegExp(
'(\\:not\\()|' + //":not("
'([-\\w]+)|' + // "tag"
'(?:\\.([-\\w]+))|' + // ".class"
'(?:\\[([-\\w*]+)(?:=([^\\]]*))?\\])|' + // "[name]", "[name=value]" or "[name*=value]"
'(\\))|' + // ")"
'(\\s*,\\s*)', // ","
'g');
/**
* A css selector contains an element name,
@ -41,11 +42,11 @@ export class CssSelector {
res.push(cssSel);
};
var cssSelector = new CssSelector();
var matcher = RegExpWrapper.matcher(_SELECTOR_REGEXP, selector);
var match: string[];
var current = cssSelector;
var inNot = false;
while (isPresent(match = RegExpMatcherWrapper.next(matcher))) {
_SELECTOR_REGEXP.lastIndex = 0;
while (isPresent(match = _SELECTOR_REGEXP.exec(selector))) {
if (isPresent(match[1])) {
if (inNot) {
throw new BaseException('Nesting :not is not allowed in a selector');

View File

@ -7,7 +7,7 @@
*/
import {ListWrapper} from './facade/collection';
import {RegExpMatcherWrapper, RegExpWrapper, StringWrapper, isBlank, isPresent} from './facade/lang';
import {StringWrapper, isBlank, isPresent} from './facade/lang';
/**
* This file is a port of shadowCSS from webcomponents.js to TypeScript.
@ -244,9 +244,9 @@ export class ShadowCss {
**/
private _extractUnscopedRulesFromCssText(cssText: string): string {
// Difference with webcomponents.js: does not handle comments
var r = '', m: any /** TODO #9100 */;
var matcher = RegExpWrapper.matcher(_cssContentUnscopedRuleRe, cssText);
while (isPresent(m = RegExpMatcherWrapper.next(matcher))) {
var r = '', m: RegExpExecArray;
_cssContentUnscopedRuleRe.lastIndex = 0;
while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
var rule = m[0];
rule = StringWrapper.replace(rule, m[2], '');
rule = StringWrapper.replace(rule, m[1], m[3]);
@ -362,7 +362,7 @@ export class ShadowCss {
private _selectorNeedsScoping(selector: string, scopeSelector: string): boolean {
var re = this._makeScopeMatcher(scopeSelector);
return !isPresent(RegExpWrapper.firstMatch(re, selector));
return !re.test(selector);
}
private _makeScopeMatcher(scopeSelector: string): RegExp {
@ -370,7 +370,7 @@ export class ShadowCss {
var rre = /\]/g;
scopeSelector = StringWrapper.replaceAll(scopeSelector, lre, '\\[');
scopeSelector = StringWrapper.replaceAll(scopeSelector, rre, '\\]');
return RegExpWrapper.create('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
}
private _applySelectorScope(selector: string, scopeSelector: string, hostSelector: string):
@ -382,7 +382,7 @@ export class ShadowCss {
// scope via name and [is=name]
private _applySimpleSelectorScope(selector: string, scopeSelector: string, hostSelector: string):
string {
if (isPresent(RegExpWrapper.firstMatch(_polyfillHostRe, selector))) {
if (_polyfillHostRe.test(selector)) {
var replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector;
selector = StringWrapper.replace(selector, _polyfillHostNoCombinator, replaceBy);
return StringWrapper.replaceAll(selector, _polyfillHostRe, replaceBy + ' ');
@ -407,9 +407,8 @@ export class ShadowCss {
var t = StringWrapper.replaceAll(p.trim(), _polyfillHostRe, '');
if (t.length > 0 && !ListWrapper.contains(splits, t) &&
!StringWrapper.contains(t, attrName)) {
var re = /([^:]*)(:*)(.*)/g;
var m = RegExpWrapper.firstMatch(re, t);
if (isPresent(m)) {
const m = t.match(/([^:]*)(:*)(.*)/);
if (m !== null) {
p = m[1] + attrName + m[2] + m[3];
}
}
@ -437,8 +436,8 @@ var _polyfillHostContext = '-shadowcsscontext';
var _parenSuffix = ')(?:\\((' +
'(?:\\([^)(]*\\)|[^)(]*)+?' +
')\\))?([^,{]*)';
var _cssColonHostRe = RegExpWrapper.create('(' + _polyfillHost + _parenSuffix, 'im');
var _cssColonHostContextRe = RegExpWrapper.create('(' + _polyfillHostContext + _parenSuffix, 'im');
var _cssColonHostRe = new RegExp('(' + _polyfillHost + _parenSuffix, 'gim');
var _cssColonHostContextRe = new RegExp('(' + _polyfillHostContext + _parenSuffix, 'gim');
var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
var _shadowDOMSelectorsRe = [
/::shadow/g, /::content/g,
@ -451,7 +450,7 @@ var _shadowDOMSelectorsRe = [
];
var _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)/g;
var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
var _polyfillHostRe = RegExpWrapper.create(_polyfillHost, 'im');
var _polyfillHostRe = new RegExp(_polyfillHost, 'im');
var _colonHostRe = /:host/gim;
var _colonHostContextRe = /:host-context/gim;

View File

@ -9,7 +9,7 @@
// Some of the code comes from WebComponents.JS
// https://github.com/webcomponents/webcomponentsjs/blob/master/src/HTMLImports/path.js
import {RegExpWrapper, StringWrapper, isBlank, isPresent} from './facade/lang';
import {StringWrapper, isBlank, isPresent} from './facade/lang';
import {UrlResolver} from './url_resolver';
@ -19,8 +19,8 @@ export class StyleWithImports {
export function isStyleUrlResolvable(url: string): boolean {
if (isBlank(url) || url.length === 0 || url[0] == '/') return false;
var schemeMatch = RegExpWrapper.firstMatch(_urlWithSchemaRe, url);
return isBlank(schemeMatch) || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
const schemeMatch = url.match(_urlWithSchemaRe);
return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
}
/**
@ -43,6 +43,4 @@ export function extractStyleUrls(
}
var _cssImportRe = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
// TODO: can't use /^[^:/?#.]+:/g due to clang-format bug:
// https://github.com/angular/angular/issues/4596
var _urlWithSchemaRe = /^([a-zA-Z\-\+\.]+):/g;
var _urlWithSchemaRe = /^([^:/?#]+):/;

View File

@ -10,7 +10,7 @@ import {Inject, Injectable, OpaqueToken, Optional, SchemaMetadata, SecurityConte
import {Console, MAX_INTERPOLATION_VALUES} from '../../core_private';
import {ListWrapper, StringMapWrapper, SetWrapper,} from '../facade/collection';
import {RegExpWrapper, isPresent, isBlank} from '../facade/lang';
import {isPresent, isBlank} from '../facade/lang';
import {BaseException} from '../facade/exceptions';
import {EmptyExpr, AST, Interpolation, ASTWithSource, TemplateBinding, RecursiveAstVisitor, BindingPipe, ParserError} from '../expression_parser/ast';
import {Parser} from '../expression_parser/parser';
@ -42,7 +42,7 @@ import {ProviderElementContext, ProviderViewContext} from '../provider_analyzer'
// Group 10 = identifier inside []
// Group 11 = identifier inside ()
const BIND_NAME_REGEXP =
/^(?:(?:(?:(bind-)|(var-)|(let-)|(ref-|#)|(on-)|(bindon-)|(animate-|@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g;
/^(?:(?:(?:(bind-)|(var-)|(let-)|(ref-|#)|(on-)|(bindon-)|(animate-|@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
const TEMPLATE_ELEMENT = 'template';
const TEMPLATE_ATTR = 'template';
@ -488,9 +488,9 @@ class TemplateParseVisitor implements html.Visitor {
targetRefs: ElementOrDirectiveRef[], targetVars: VariableAst[]): boolean {
const attrName = this._normalizeAttributeName(attr.name);
const attrValue = attr.value;
const bindParts = RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName);
const bindParts = attrName.match(BIND_NAME_REGEXP);
let hasBinding = false;
if (isPresent(bindParts)) {
if (bindParts !== null) {
hasBinding = true;
if (isPresent(bindParts[1])) { // match: bind-prop
this._parsePropertyOrAnimation(

View File

@ -8,7 +8,7 @@
import {Inject, Injectable, PACKAGE_ROOT_URL} from '@angular/core';
import {StringWrapper, isPresent, isBlank, RegExpWrapper,} from './facade/lang';
import {StringWrapper, isBlank, isPresent} from './facade/lang';
const _ASSET_SCHEME = 'asset:';
@ -211,7 +211,7 @@ function _buildFromEncodedParts(
* @type {!RegExp}
* @internal
*/
var _splitRe = RegExpWrapper.create(
var _splitRe = new RegExp(
'^' +
'(?:' +
'([^:/?#.]+)' + // scheme - ignore special characters
@ -260,7 +260,7 @@ enum _ComponentIndex {
* arbitrary strings may still look like path names.
*/
function _split(uri: string): Array<string|any> {
return RegExpWrapper.firstMatch(_splitRe, uri);
return uri.match(_splitRe);
}
/**

View File

@ -9,7 +9,7 @@
import {describe, beforeEach, it, expect, ddescribe, iit,} from '@angular/core/testing/testing_internal';
import {ShadowCss, processRules, CssRule} from '@angular/compiler/src/shadow_css';
import {RegExpWrapper, StringWrapper, isPresent} from '../src/facade/lang';
import {StringWrapper, isPresent} from '../src/facade/lang';
import {normalizeCSS} from '@angular/platform-browser/testing/browser_util';
export function main() {

View File

@ -198,7 +198,7 @@ function dateFormatter(format: string, date: Date, locale: string): string {
if (datePartsFormatterCache.has(format)) {
parts = datePartsFormatterCache.get(format);
} else {
var matchs = DATE_FORMATS_SPLIT.exec(format);
const matches = DATE_FORMATS_SPLIT.exec(format);
while (format) {
match = DATE_FORMATS_SPLIT.exec(format);

View File

@ -312,50 +312,6 @@ export class NumberWrapper {
export var RegExp = _global.RegExp;
export class RegExpWrapper {
static create(regExpStr: string, flags: string = ''): RegExp {
flags = flags.replace(/g/g, '');
return new _global.RegExp(regExpStr, flags + 'g');
}
static firstMatch(regExp: RegExp, input: string): RegExpExecArray {
// Reset multimatch regex state
regExp.lastIndex = 0;
return regExp.exec(input);
}
static test(regExp: RegExp, input: string): boolean {
regExp.lastIndex = 0;
return regExp.test(input);
}
static matcher(regExp: RegExp, input: string): {re: RegExp; input: string} {
// Reset regex state for the case
// someone did not loop over all matches
// last time.
regExp.lastIndex = 0;
return {re: regExp, input: input};
}
static replaceAll(regExp: RegExp, input: string, replace: Function): string {
let c = regExp.exec(input);
let res = '';
regExp.lastIndex = 0;
let prev = 0;
while (c) {
res += input.substring(prev, c.index);
res += replace(c);
prev = c.index + c[0].length;
regExp.lastIndex = prev;
c = regExp.exec(input);
}
res += input.substring(prev);
return res;
}
}
export class RegExpMatcherWrapper {
static next(matcher: {re: RegExp; input: string}): RegExpExecArray {
return matcher.re.exec(matcher.input);
}
}
export class FunctionWrapper {
static apply(fn: Function, posArgs: any): any { return fn.apply(null, posArgs); }

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {NumberWrapper, RegExpMatcherWrapper, RegExpWrapper, StringWrapper, escapeRegExp, hasConstructor, isPresent, isPromise, resolveEnumToken} from '../src/lang';
import {NumberWrapper, StringWrapper, escapeRegExp, hasConstructor, isPresent, isPromise, resolveEnumToken} from '../src/lang';
enum UsefulEnum {
MyToken,
@ -18,42 +18,11 @@ class MySubclass extends MySuperclass {}
export function main() {
describe('RegExp', () => {
it('should expose the index for each match', () => {
var re = /(!)/g;
var matcher = RegExpWrapper.matcher(re, '0!23!567!!');
var indexes: number[] = [];
var m: any /** TODO #9100 */;
while (isPresent(m = RegExpMatcherWrapper.next(matcher))) {
indexes.push(m.index);
expect(m[0]).toEqual('!');
expect(m[1]).toEqual('!');
expect(m.length).toBe(2);
}
expect(indexes).toEqual([1, 4, 8, 9]);
});
it('should reset before it is reused', () => {
var re = /^['"]/g;
var str = '\'';
expect(RegExpWrapper.test(re, str)).toEqual(true);
// If not reset, the second attempt to test results in false
expect(RegExpWrapper.test(re, str)).toEqual(true);
});
it('should implement replace all', () => {
let re = /(\d)+/g;
let m =
RegExpWrapper.replaceAll(re, 'a1b2c', (match: any /** TODO #9100 */) => `!${match[1]}!`);
expect(m).toEqual('a!1!b!2!c');
});
it('should escape regexp', () => {
expect(RegExpWrapper.firstMatch(new RegExp(escapeRegExp('b')), 'abc')).toBeTruthy();
expect(RegExpWrapper.firstMatch(new RegExp(escapeRegExp('b')), 'adc')).toBeFalsy();
expect(RegExpWrapper.firstMatch(new RegExp(escapeRegExp('a.b')), 'a.b')).toBeTruthy();
expect(RegExpWrapper.firstMatch(new RegExp(escapeRegExp('axb')), 'a.b')).toBeFalsy();
expect(new RegExp(escapeRegExp('b')).exec('abc')).toBeTruthy();
expect(new RegExp(escapeRegExp('b')).exec('adc')).toBeFalsy();
expect(new RegExp(escapeRegExp('a.b')).exec('a.b')).toBeTruthy();
expect(new RegExp(escapeRegExp('a.b')).exec('axb')).toBeFalsy();
});
});

View File

@ -10,7 +10,7 @@ import {Inject, Injectable, OpaqueToken, RenderComponentType, Renderer, RootRend
import {StringMapWrapper} from '../facade/collection';
import {BaseException} from '../facade/exceptions';
import {Json, RegExpWrapper, StringWrapper, isArray, isBlank, isPresent, isString, stringify} from '../facade/lang';
import {Json, StringWrapper, isArray, isBlank, isPresent, isString, stringify} from '../facade/lang';
import {DomSharedStylesHost} from './shared_styles_host';
@ -28,7 +28,7 @@ const NAMESPACE_URIS = {
'xhtml': 'http://www.w3.org/1999/xhtml'
};
const TEMPLATE_COMMENT_TEXT = 'template bindings={}';
var TEMPLATE_BINDINGS_EXP = /^template bindings=(.*)$/g;
var TEMPLATE_BINDINGS_EXP = /^template bindings=(.*)$/;
export abstract class DomRootRenderer implements RootRenderer {
protected registeredComponents: Map<string, DomRenderer> = new Map<string, DomRenderer>();
@ -197,9 +197,8 @@ export class DomRenderer implements Renderer {
setBindingDebugInfo(renderElement: any, propertyName: string, propertyValue: string): void {
var dashCasedPropertyName = camelCaseToDashCase(propertyName);
if (getDOM().isCommentNode(renderElement)) {
var existingBindings = RegExpWrapper.firstMatch(
TEMPLATE_BINDINGS_EXP,
StringWrapper.replaceAll(getDOM().getText(renderElement), /\n/g, ''));
const existingBindings = StringWrapper.replaceAll(getDOM().getText(renderElement), /\n/g, '')
.match(TEMPLATE_BINDINGS_EXP);
var parsedBindings = Json.parse(existingBindings[1]);
(parsedBindings as any /** TODO #9100 */)[dashCasedPropertyName] = propertyValue;
getDOM().setText(
@ -298,12 +297,12 @@ function _flattenStyles(compId: string, styles: Array<any|any[]>, target: string
return target;
}
var NS_PREFIX_RE = /^:([^:]+):(.+)/g;
const NS_PREFIX_RE = /^:([^:]+):(.+)$/;
function splitNamespace(name: string): string[] {
if (name[0] != ':') {
return [null, name];
}
let match = RegExpWrapper.firstMatch(NS_PREFIX_RE, name);
const match = name.match(NS_PREFIX_RE);
return [match[1], match[2]];
}

View File

@ -86,7 +86,7 @@ export function sanitizeStyle(value: string): string {
// Single url(...) values are supported, but only for URLs that sanitize cleanly. See above for
// reasoning behind this.
let urlMatch = URL_RE.exec(value);
const urlMatch = value.match(URL_RE);
if ((urlMatch && sanitizeUrl(urlMatch[1]) === urlMatch[1]) ||
value.match(SAFE_STYLE_VALUE) && hasBalancedQuotes(value)) {
return value; // Safe style values.

View File

@ -8,7 +8,7 @@
import {getDOM} from '../src/dom/dom_adapter';
import {ListWrapper} from '../src/facade/collection';
import {RegExp, RegExpWrapper, StringWrapper, global, isPresent, isString} from '../src/facade/lang';
import {RegExp, StringWrapper, global, isPresent, isString} from '../src/facade/lang';
export class BrowserDetection {
private _overrideUa: string;

View File

@ -8,7 +8,7 @@
import {StringMapWrapper} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions';
import {RegExpWrapper, StringWrapper, isBlank, isPresent} from '../../facade/lang';
import {StringWrapper, isBlank, isPresent} from '../../facade/lang';
import {RootUrl, Url, convertUrlParamsToArray} from '../../url_parser';
import {TouchMap, normalizeString} from '../../utils';
@ -60,7 +60,7 @@ class StaticPathSegment implements PathSegment {
* a matching `Instruction`.
*/
class DynamicPathSegment implements PathSegment {
static paramMatcher = /^:([^\/]+)$/g;
static paramMatcher = /^:([^\/]+)$/;
specificity = '1';
hash = ':';
constructor(public name: string) {}
@ -80,7 +80,7 @@ class DynamicPathSegment implements PathSegment {
* be provided to a matching `Instruction`.
*/
class StarPathSegment implements PathSegment {
static wildcardMatcher = /^\*([^\/]+)$/g;
static wildcardMatcher = /^\*([^\/]+)$/;
specificity = '0';
hash = '*';
constructor(public name: string) {}
@ -211,12 +211,11 @@ export class ParamRoutePath implements RoutePath {
var limit = segmentStrings.length - 1;
for (var i = 0; i <= limit; i++) {
var segment = segmentStrings[i], match: any /** TODO #9100 */;
var segment = segmentStrings[i], match: RegExpMatchArray;
if (isPresent(match = RegExpWrapper.firstMatch(DynamicPathSegment.paramMatcher, segment))) {
if (isPresent(match = segment.match(DynamicPathSegment.paramMatcher))) {
this._segments.push(new DynamicPathSegment(match[1]));
} else if (isPresent(
match = RegExpWrapper.firstMatch(StarPathSegment.wildcardMatcher, segment))) {
} else if (isPresent(match = segment.match(StarPathSegment.wildcardMatcher))) {
this._segments.push(new StarPathSegment(match[1]));
} else if (segment == '...') {
if (i < limit) {
@ -272,13 +271,13 @@ export class ParamRoutePath implements RoutePath {
throw new BaseException(
`Path "${path}" should not include "#". Use "HashLocationStrategy" instead.`);
}
var illegalCharacter = RegExpWrapper.firstMatch(ParamRoutePath.RESERVED_CHARS, path);
const illegalCharacter = path.match(ParamRoutePath.RESERVED_CHARS);
if (isPresent(illegalCharacter)) {
throw new BaseException(
`Path "${path}" contains "${illegalCharacter[0]}" which is not allowed in a route config.`);
}
}
static RESERVED_CHARS = RegExpWrapper.create('//|\\(|\\)|;|\\?|=');
static RESERVED_CHARS = new RegExp('//|\\(|\\)|;|\\?|=');
}
let REGEXP_PERCENT = /%/g;

View File

@ -8,7 +8,7 @@
import {BaseException} from '@angular/core';
import {RegExpMatcherWrapper, RegExpWrapper, isBlank} from '../../facade/lang';
import {isBlank} from '../../facade/lang';
import {Url} from '../../url_parser';
import {GeneratedUrl, MatchedUrl, RoutePath} from './route_path';
@ -20,10 +20,8 @@ function computeNumberOfRegexGroups(regex: string): number {
// cleverly compute regex groups by appending an alternative empty matching
// pattern and match against an empty string, the resulting match still
// receives all the other groups
var test_regex = RegExpWrapper.create(regex + '|');
var matcher = RegExpWrapper.matcher(test_regex, '');
var match = RegExpMatcherWrapper.next(matcher);
return match.length;
var testRegex = new RegExp(regex + '|');
return testRegex.exec('').length;
}
export class RegexRoutePath implements RoutePath {
@ -37,7 +35,7 @@ export class RegexRoutePath implements RoutePath {
private _reString: string, private _serializer: RegexSerializer,
private _groupNames?: Array<string>) {
this.hash = this._reString;
this._regex = RegExpWrapper.create(this._reString);
this._regex = new RegExp(this._reString);
if (this._groupNames != null) {
var groups = computeNumberOfRegexGroups(this._reString);
if (groups != _groupNames.length) {
@ -52,8 +50,7 @@ each matching group and a name for the complete match as its first element of re
matchUrl(url: Url): MatchedUrl {
var urlPath = url.toString();
var params: {[key: string]: string} = {};
var matcher = RegExpWrapper.matcher(this._regex, urlPath);
var match = RegExpMatcherWrapper.next(matcher);
var match = urlPath.match(this._regex);
if (isBlank(match)) {
return null;

View File

@ -8,7 +8,7 @@
import {StringMapWrapper} from '../src/facade/collection';
import {BaseException} from '../src/facade/exceptions';
import {RegExpWrapper, isBlank, isPresent} from '../src/facade/lang';
import {isBlank, isPresent} from '../src/facade/lang';
export function convertUrlParamsToArray(urlParams: {[key: string]: any}): string[] {
var paramsArray: any[] /** TODO #9100 */ = [];
@ -89,15 +89,15 @@ export function pathSegmentsToUrl(pathSegments: string[]): Url {
return url;
}
var SEGMENT_RE = RegExpWrapper.create('^[^\\/\\(\\)\\?;=&#]+');
const SEGMENT_RE = /^[^\/\(\)\?;=&#]+/;
function matchUrlSegment(str: string): string {
var match = RegExpWrapper.firstMatch(SEGMENT_RE, str);
return isPresent(match) ? match[0] : '';
const match = str.match(SEGMENT_RE);
return match !== null ? match[0] : '';
}
var QUERY_PARAM_VALUE_RE = RegExpWrapper.create('^[^\\(\\)\\?;&#]+');
const QUERY_PARAM_VALUE_RE = /^[^\(\)\?;&#]+/;
function matchUrlQueryParamValue(str: string): string {
var match = RegExpWrapper.firstMatch(QUERY_PARAM_VALUE_RE, str);
return isPresent(match) ? match[0] : '';
var match = str.match(QUERY_PARAM_VALUE_RE);
return match !== null ? match[0] : '';
}
export class UrlParser {

View File

@ -257,21 +257,21 @@ function pairs<T>(obj: {[key: string]: T}): Pair<string, T>[] {
const SEGMENT_RE = /^[^\/\(\)\?;=&#]+/;
function matchSegments(str: string): string {
SEGMENT_RE.lastIndex = 0;
const match = SEGMENT_RE.exec(str);
const match = str.match(SEGMENT_RE);
return match ? match[0] : '';
}
const QUERY_PARAM_RE = /^[^=\?&#]+/;
function matchQueryParams(str: string): string {
QUERY_PARAM_RE.lastIndex = 0;
const match = SEGMENT_RE.exec(str);
const match = str.match(SEGMENT_RE);
return match ? match[0] : '';
}
const QUERY_PARAM_VALUE_RE = /^[^\?&#]+/;
function matchUrlQueryParamValue(str: string): string {
QUERY_PARAM_VALUE_RE.lastIndex = 0;
const match = QUERY_PARAM_VALUE_RE.exec(str);
const match = str.match(QUERY_PARAM_VALUE_RE);
return match ? match[0] : '';
}

View File

@ -10,7 +10,7 @@ import {OpaqueToken} from '@angular/core/src/di';
import {PromiseWrapper, TimerWrapper} from '@angular/facade/src/async';
import {ListWrapper, StringMapWrapper} from '@angular/facade/src/collection';
import {BaseException, WrappedException} from '@angular/facade/src/exceptions';
import {Math, NumberWrapper, RegExpWrapper, StringWrapper, isBlank, isPresent} from '@angular/facade/src/lang';
import {Math, NumberWrapper, StringWrapper, isBlank, isPresent} from '@angular/facade/src/lang';
import {Options} from '../common_options';
import {Metric} from '../metric';
@ -245,7 +245,7 @@ export class PerflogMetric extends Metric {
var ph = event['ph'];
var name = event['name'];
var microIterations = 1;
var microIterationsMatch = RegExpWrapper.firstMatch(_MICRO_ITERATIONS_REGEX, name);
var microIterationsMatch = name.match(_MICRO_ITERATIONS_REGEX);
if (isPresent(microIterationsMatch)) {
name = microIterationsMatch[1];
microIterations = NumberWrapper.parseInt(microIterationsMatch[2], 10);
@ -379,7 +379,7 @@ export class PerflogMetric extends Metric {
private _markName(index) { return `${_MARK_NAME_PREFIX}${index}`; }
}
var _MICRO_ITERATIONS_REGEX = /(.+)\*(\d+)$/g;
var _MICRO_ITERATIONS_REGEX = /(.+)\*(\d+)$/;
var _MAX_RETRY_COUNT = 20;
var _MARK_NAME_PREFIX = 'benchpress';

View File

@ -8,7 +8,7 @@
import {ListWrapper, StringMapWrapper} from '@angular/facade/src/collection';
import {BaseException, WrappedException} from '@angular/facade/src/exceptions';
import {Json, NumberWrapper, RegExpWrapper, StringWrapper, isBlank, isPresent} from '@angular/facade/src/lang';
import {Json, NumberWrapper, StringWrapper, isBlank, isPresent} from '@angular/facade/src/lang';
import {Options} from '../common_options';
import {WebDriverAdapter} from '../web_driver_adapter';

View File

@ -7,7 +7,7 @@
*/
import {BaseException, WrappedException} from '@angular/facade/src/exceptions';
import {Json, RegExpWrapper, StringWrapper, isBlank, isPresent} from '@angular/facade/src/lang';
import {Json, StringWrapper, isBlank, isPresent} from '@angular/facade/src/lang';
import {WebDriverAdapter} from '../web_driver_adapter';
import {PerfLogFeatures, WebDriverExtension} from '../web_driver_extension';

View File

@ -8,7 +8,7 @@
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {PromiseWrapper} from '@angular/facade/src/async';
import {DateWrapper, Json, RegExpWrapper, isPresent} from '@angular/facade/src/lang';
import {DateWrapper, Json, isPresent} from '@angular/facade/src/lang';
import {MeasureValues, Options, ReflectiveInjector, SampleDescription} from 'benchpress/common';
import {JsonFileReporter} from 'benchpress/src/reporter/json_file_reporter';
@ -44,8 +44,8 @@ export function main() {
.reportSample(
[mv(0, 0, {'a': 3, 'b': 6})],
[mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]);
var regExp = /somePath\/someId_\d+\.json/g;
expect(isPresent(RegExpWrapper.firstMatch(regExp, loggedFile['filename']))).toBe(true);
var regExp = /somePath\/someId_\d+\.json/;
expect(isPresent(loggedFile['filename'].match(regExp))).toBe(true);
var parsedContent = Json.parse(loggedFile['content']);
expect(parsedContent).toEqual({
'description':

View File

@ -23,10 +23,10 @@ describe('sourcemaps', function() {
// so that the browser logs can be read out!
browser.executeScript('1+1');
browser.manage().logs().get('browser').then(function(logs) {
var errorLine: any /** TODO #9100 */ = null;
var errorColumn: any /** TODO #9100 */ = null;
var errorLine: number = null;
var errorColumn: number = null;
logs.forEach(function(log) {
var match = /\.createError\s+\(.+:(\d+):(\d+)/m.exec(log.message);
const match = log.message.match(/\.createError\s+\(.+:(\d+):(\d+)/m);
if (match) {
errorLine = parseInt(match[1]);
errorColumn = parseInt(match[2]);

View File

@ -18,14 +18,14 @@ import {
} from '@angular/common';
import {Component, Directive, Host} from '@angular/core';
import {RegExpWrapper, print, isPresent} from '@angular/core/src/facade/lang';
import {print, isPresent} from '@angular/core/src/facade/lang';
import {AbstractControl} from '@angular/common';
/**
* Custom validator.
*/
function creditCardValidator(c: AbstractControl): {[key: string]: boolean} {
if (isPresent(c.value) && RegExpWrapper.test(/^\d{16}$/g, c.value)) {
if (isPresent(c.value) && /^\d{16}$/.test(c.value)) {
return null;
} else {
return {"invalidCreditCard": true};

View File

@ -19,7 +19,7 @@ import {
NgForm
} from '@angular/common';
import {RegExpWrapper, print, isPresent} from '@angular/core/src/facade/lang';
import {print, isPresent} from '@angular/core/src/facade/lang';
/**
* A domain model we are binding the form controls to.
@ -40,7 +40,7 @@ class CheckoutModel {
* Custom validator.
*/
function creditCardValidator(c: any /** TODO #9100 */): {[key: string]: boolean} {
if (isPresent(c.value) && RegExpWrapper.test(/^\d{16}$/g, c.value)) {
if (isPresent(c.value) && /^\d{16}$/.test(c.value)) {
return null;
} else {
return {"invalidCreditCard": true};