refactor(RegExp): use /.../ to create RegExp literal

fixes #2691
This commit is contained in:
Victor Berchet 2015-06-23 12:46:38 +02:00
parent 258da88765
commit 447926dc08
17 changed files with 62 additions and 84 deletions

View File

@ -1,11 +1,5 @@
import {Injectable} from 'angular2/src/di/decorators';
import {
isBlank,
isPresent,
BaseException,
StringWrapper,
RegExpWrapper
} from 'angular2/src/facade/lang';
import {isBlank, isPresent, BaseException, StringWrapper} from 'angular2/src/facade/lang';
import {ListWrapper, List} from 'angular2/src/facade/collection';
import {
Lexer,
@ -52,7 +46,7 @@ import {
var _implicitReceiver = new ImplicitReceiver();
// TODO(tbosch): Cannot make this const/final right now because of the transpiler...
var INTERPOLATION_REGEXP = RegExpWrapper.create('\\{\\{(.*?)\\}\\}');
var INTERPOLATION_REGEXP = /\{\{(.*?)\}\}/g;
@Injectable()
export class Parser {

View File

@ -1,10 +1,4 @@
import {
CONST_EXPR,
isPresent,
NumberWrapper,
StringWrapper,
RegExpWrapper
} from 'angular2/src/facade/lang';
import {CONST_EXPR, isPresent, NumberWrapper, StringWrapper} from 'angular2/src/facade/lang';
import {MapWrapper, Map, ListWrapper, List} from 'angular2/src/facade/collection';
import {Injectable, bind, Binding} from 'angular2/di';
import {AppViewListener} from 'angular2/src/core/compiler/view_listener';
@ -16,7 +10,6 @@ import {DebugElement} from './debug_element';
const NG_ID_PROPERTY = 'ngid';
const INSPECT_GLOBAL_NAME = 'ngProbe';
var NG_ID_SEPARATOR_RE = RegExpWrapper.create('#');
var NG_ID_SEPARATOR = '#';
// Need to keep the views in a global Map so that multiple angular apps are supported
@ -34,7 +27,7 @@ function _setElementId(element, indices: List<number>) {
function _getElementId(element): List<number> {
var elId = DOM.getData(element, NG_ID_PROPERTY);
if (isPresent(elId)) {
return ListWrapper.map(StringWrapper.split(elId, NG_ID_SEPARATOR_RE),
return ListWrapper.map(elId.split(NG_ID_SEPARATOR),
(partStr) => NumberWrapper.parseInt(partStr, 10));
} else {
return null;

View File

@ -130,11 +130,6 @@ export class ProtoViewDto {
}
}
// group 1: property from "[property]"
// group 2: event from "(event)"
// group 3: action from "@action"
var hostRegExp = RegExpWrapper.create('^(?:(?:\\[([^\\]]+)\\])|(?:\\(([^\\)]+)\\))|(?:@(.+)))$');
export class DirectiveMetadata {
static get DIRECTIVE_TYPE() { return 0; }
static get COMPONENT_TYPE() { return 1; }
@ -156,6 +151,10 @@ export class DirectiveMetadata {
hostProperties: Map<string, string>;
hostAttributes: Map<string, string>;
hostActions: Map<string, string>;
// group 1: "property" from "[property]"
// group 2: "event" from "(event)"
// group 3: "action" from "@action"
private static _hostRegExp = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\))|(?:@(.+)))$/g;
constructor({id, selector, compileChildren, events, hostListeners, hostProperties, hostAttributes,
hostActions, properties, readAttributes, type, callOnDestroy, callOnChange,
@ -225,7 +224,7 @@ export class DirectiveMetadata {
if (isPresent(host)) {
MapWrapper.forEach(host, (value: string, key: string) => {
var matches = RegExpWrapper.firstMatch(hostRegExp, key);
var matches = RegExpWrapper.firstMatch(DirectiveMetadata._hostRegExp, key);
if (isBlank(matches)) {
hostAttributes.set(key, value);
} else if (isPresent(matches[1])) {

View File

@ -17,8 +17,8 @@ import {dashCaseToCamelCase} from '../util';
// Group 6 = idenitifer inside [()]
// Group 7 = idenitifer inside []
// Group 8 = identifier inside ()
var BIND_NAME_REGEXP = RegExpWrapper.create(
'^(?:(?:(?:(bind-)|(var-|#)|(on-)|(bindon-))(.+))|\\[\\(([^\\)]+)\\)\\]|\\[([^\\]]+)\\]|\\(([^\\)]+)\\))$');
var BIND_NAME_REGEXP =
/^(?:(?:(?:(bind-)|(var-|#)|(on-)|(bindon-))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g;
/**
* Parses the property bindings on a single element.
*/

View File

@ -131,9 +131,9 @@ function _wrapInMediaRule(css: string, query: string): string {
return (isBlank(query)) ? css : `@media ${query} {\n${css}\n}`;
}
var _importRe = RegExpWrapper.create('@import\\s+([^;]+);');
var _importRe = /@import\s+([^;]+);/g;
var _urlRe = RegExpWrapper.create(
'url\\(\\s*?[\'"]?([^\'")]+)[\'"]?|' + // url(url) or url('url') or url("url")
'[\'"]([^\'")]+)[\'"]' // "url" or 'url'
);
var _mediaQueryRe = RegExpWrapper.create('[\'"][^\'"]+[\'"]\\s*\\)?\\s*(.*)');
var _mediaQueryRe = /['"][^'"]+['"]\s*\)?\s*(.*)/g;

View File

@ -2,7 +2,7 @@
// https://github.com/webcomponents/webcomponentsjs/blob/master/src/HTMLImports/path.js
import {Injectable} from 'angular2/di';
import {RegExp, RegExpWrapper, StringWrapper} from 'angular2/src/facade/lang';
import {RegExp, StringWrapper} from 'angular2/src/facade/lang';
import {UrlResolver} from 'angular2/src/services/url_resolver';
/**
@ -31,6 +31,6 @@ export class StyleUrlResolver {
}
}
var _cssUrlRe = RegExpWrapper.create('(url\\()([^)]*)(\\))');
var _cssImportRe = RegExpWrapper.create('(@import[\\s]+(?!url\\())[\'"]([^\'"]*)[\'"](.*;)');
var _quoteRe = RegExpWrapper.create('[\'"]');
var _cssUrlRe = /(url\()([^)]*)(\))/g;
var _cssImportRe = /(@import[\s]+(?!url\())['"]([^'"]*)['"](.*;)/g;
var _quoteRe = /['"]/g;

View File

@ -403,8 +403,8 @@ export class ShadowCss {
}
_makeScopeMatcher(scopeSelector: string): RegExp {
var lre = RegExpWrapper.create('\\[');
var rre = RegExpWrapper.create('\\]');
var lre = /\[/g;
var rre = /\]/g;
scopeSelector = StringWrapper.replaceAll(scopeSelector, lre, '\\[');
scopeSelector = StringWrapper.replaceAll(scopeSelector, rre, '\\]');
return RegExpWrapper.create('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
@ -429,7 +429,7 @@ export class ShadowCss {
// return a selector with [name] suffix on each simple selector
// e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name]
_applyStrictSelectorScope(selector: string, scopeSelector: string): string {
var isRe = RegExpWrapper.create('\\[is=([^\\]]*)\\]');
var isRe = /\[is=([^\]]*)\]/g;
scopeSelector = StringWrapper.replaceAllMapped(scopeSelector, isRe, (m) => m[1]);
var splits = [' ', '>', '+', '~'], scoped = selector, attrName = '[' + scopeSelector + ']';
for (var i = 0; i < splits.length; i++) {
@ -440,7 +440,7 @@ export class ShadowCss {
var t = StringWrapper.replaceAll(p.trim(), _polyfillHostRe, '');
if (t.length > 0 && !ListWrapper.contains(splits, t) &&
!StringWrapper.contains(t, attrName)) {
var re = RegExpWrapper.create('([^:]*)(:*)(.*)');
var re = /([^:]*)(:*)(.*)/g;
var m = RegExpWrapper.firstMatch(re, t);
if (isPresent(m)) {
p = m[1] + attrName + m[2] + m[3];
@ -463,10 +463,10 @@ export class ShadowCss {
// TODO(sorvell): Safari cssom incorrectly removes quotes from the content
// property. (https://bugs.webkit.org/show_bug.cgi?id=118045)
// don't replace attr rules
var attrRe = RegExpWrapper.create('[\'"]+|attr');
var attrRe = /['"]+|attr/g;
if (rule.style.content.length > 0 &&
!isPresent(RegExpWrapper.firstMatch(attrRe, rule.style.content))) {
var contentRe = RegExpWrapper.create('content:[^;]*;');
var contentRe = /content:[^;]*;/g;
cssText =
StringWrapper.replaceAll(cssText, contentRe, 'content: \'' + rule.style.content + '\';');
}
@ -487,13 +487,11 @@ export class ShadowCss {
return cssText;
}
}
var _cssContentNextSelectorRe = RegExpWrapper.create(
'polyfill-next-selector[^}]*content:[\\s]*?[\'"](.*?)[\'"][;\\s]*}([^{]*?){', 'im');
var _cssContentRuleRe =
RegExpWrapper.create('(polyfill-rule)[^}]*(content:[\\s]*[\'"](.*?)[\'"])[;\\s]*[^}]*}', 'im');
var _cssContentUnscopedRuleRe = RegExpWrapper.create(
'(polyfill-unscoped-rule)[^}]*(content:[\\s]*[\'"](.*?)[\'"])[;\\s]*[^}]*}', 'im');
var _cssContentNextSelectorRe =
/polyfill-next-selector[^}]*content:[\s]*?['"](.*?)['"][;\s]*}([^{]*?){/gim;
var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim;
var _cssContentUnscopedRuleRe =
/(polyfill-unscoped-rule)[^}]*(content:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim;
var _polyfillHost = '-shadowcsshost';
// note: :host-context pre-processed to -shadowcsshostcontext.
var _polyfillHostContext = '-shadowcsscontext';
@ -504,18 +502,21 @@ var _cssColonHostRe = RegExpWrapper.create('(' + _polyfillHost + _parenSuffix, '
var _cssColonHostContextRe = RegExpWrapper.create('(' + _polyfillHostContext + _parenSuffix, 'im');
var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
var _shadowDOMSelectorsRe = [
RegExpWrapper.create('>>>'),
RegExpWrapper.create('::shadow'),
RegExpWrapper.create('::content'),
/>>>/g,
/::shadow/g,
/::content/g,
// Deprecated selectors
RegExpWrapper.create('/deep/'), // former >>>
RegExpWrapper.create('/shadow-deep/'), // former /deep/
RegExpWrapper.create('/shadow/'), // former ::shadow
// TODO(vicb): see https://github.com/angular/clang-format/issues/16
// clang-format off
/\/deep\//g, // former >>>
/\/shadow-deep\//g, // former /deep/
/\/shadow\//g, // former ::shadow
// clanf-format on
];
var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
var _polyfillHostRe = RegExpWrapper.create(_polyfillHost, 'im');
var _colonHostRe = RegExpWrapper.create(':host', 'im');
var _colonHostContextRe = RegExpWrapper.create(':host-context', 'im');
var _colonHostRe = /:host/gim;
var _colonHostContextRe = /:host-context/gim;
function _cssToRules(cssText: string) {
return DOM.cssToRules(cssText);

View File

@ -1,12 +1,12 @@
import {StringWrapper, RegExpWrapper, isPresent} from 'angular2/src/facade/lang';
import {StringWrapper, isPresent} from 'angular2/src/facade/lang';
export const NG_BINDING_CLASS_SELECTOR = '.ng-binding';
export const NG_BINDING_CLASS = 'ng-binding';
export const EVENT_TARGET_SEPARATOR = ':';
var CAMEL_CASE_REGEXP = RegExpWrapper.create('([A-Z])');
var DASH_CASE_REGEXP = RegExpWrapper.create('-([a-z])');
var CAMEL_CASE_REGEXP = /([A-Z])/g;
var DASH_CASE_REGEXP = /-([a-z])/g;
export function camelCaseToDashCase(input: string): string {
return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP,

View File

@ -78,8 +78,8 @@ class StarSegment {
}
var paramMatcher = RegExpWrapper.create("^:([^\/]+)$");
var wildcardMatcher = RegExpWrapper.create("^\\*([^\/]+)$");
var paramMatcher = /^:([^\/]+)$/g;
var wildcardMatcher = /^\*([^\/]+)$/g;
function parsePathString(route: string): StringMap<string, any> {
// normalize route as not starting with a "/". Recognition will

View File

@ -49,12 +49,11 @@ export function containsRegexp(input: string): RegExp {
}
export function normalizeCSS(css: string): string {
css = StringWrapper.replaceAll(css, RegExpWrapper.create('\\s+'), ' ');
css = StringWrapper.replaceAll(css, RegExpWrapper.create(':\\s'), ':');
css = StringWrapper.replaceAll(css, RegExpWrapper.create("\\'"), '"');
css = StringWrapper.replaceAllMapped(css, RegExpWrapper.create('url\\(\\"(.+)\\"\\)'),
(match) => `url(${match[1]})`);
css = StringWrapper.replaceAllMapped(css, RegExpWrapper.create('\\[(.+)=([^"\\]]+)\\]'),
css = StringWrapper.replaceAll(css, /\s+/g, ' ');
css = StringWrapper.replaceAll(css, /:\s/g, ':');
css = StringWrapper.replaceAll(css, /'"/g, '"');
css = StringWrapper.replaceAllMapped(css, /url\(\"(.+)\\"\)/g, (match) => `url(${match[1]})`);
css = StringWrapper.replaceAllMapped(css, /\[(.+)=([^"\]]+)\]/g,
(match) => `[${match[1]}="${match[2]}"]`);
return css;
}

View File

@ -23,11 +23,10 @@ import {
} from 'angular2/src/change_detection/parser/ast';
import {StringWrapper, RegExpWrapper, isPresent, isString} from 'angular2/src/facade/lang';
var quoteRegExp = RegExpWrapper.create('"');
import {StringWrapper, isPresent, isString} from 'angular2/src/facade/lang';
export class Unparser implements AstVisitor {
private static _quoteRegExp = /"/g;
private _expression: string;
unparse(ast: AST) {
@ -151,7 +150,7 @@ export class Unparser implements AstVisitor {
visitLiteralPrimitive(ast: LiteralPrimitive) {
if (isString(ast.value)) {
this._expression += `"${StringWrapper.replaceAll(ast.value, quoteRegExp, '\"')}"`;
this._expression += `"${StringWrapper.replaceAll(ast.value, Unparser._quoteRegExp, '\"')}"`;
} else {
this._expression += `${ast.value}`;
}

View File

@ -10,7 +10,7 @@ import {
export function main() {
describe('RegExp', () => {
it('should expose the index for each match', () => {
var re = RegExpWrapper.create('(!)');
var re = /(!)/g;
var matcher = RegExpWrapper.matcher(re, '0!23!567!!');
var indexes = [];
var m;

View File

@ -20,7 +20,7 @@ export function main() {
function s(css: string, contentAttr: string, hostAttr: string = '') {
var shadowCss = new ShadowCss();
var shim = shadowCss.shimCssText(css, contentAttr, hostAttr);
var nlRegexp = RegExpWrapper.create('\\n');
var nlRegexp = /\n/g;
return normalizeCSS(StringWrapper.replaceAll(shim, nlRegexp, ''));
}
@ -61,8 +61,7 @@ export function main() {
isPresent(DOM.defaultDoc().body.style.animationName)) {
it('should handle keyframes rules', () => {
var css = '@keyframes foo {0% {transform: translate(-50%) scaleX(0);}}';
var passRe = RegExpWrapper.create(
'@keyframes foo {\\s*0% {\\s*transform:translate\\(-50%\\) scaleX\\(0\\);\\s*}\\s*}');
var passRe = /@keyframes foo {\s*0% {\s*transform:translate\(-50%\) scaleX\(0\);\s*}\s*}/g;
expect(RegExpWrapper.test(passRe, s(css, 'a'))).toEqual(true);
});
}
@ -70,8 +69,8 @@ export function main() {
if (DOM.getUserAgent().indexOf('AppleWebKit') > -1) {
it('should handle -webkit-keyframes rules', () => {
var css = '@-webkit-keyframes foo {0% {-webkit-transform: translate(-50%) scaleX(0);}}';
var passRe = RegExpWrapper.create(
'@-webkit-keyframes foo {\\s*0% {\\s*(-webkit-)*transform:translate\\(-50%\\) scaleX\\(0\\);\\s*}}');
var passRe =
/@-webkit-keyframes foo {\s*0% {\s*(-webkit-)*transform:translate\(-50%\) scaleX\(0\);\s*}}/g;
expect(RegExpWrapper.test(passRe, s(css, 'a'))).toEqual(true);
});
}

View File

@ -1,13 +1,7 @@
import {Component, View, Parent, onDestroy, onChange, onAllChangesDone} from 'angular2/angular2';
import {ListWrapper} from 'angular2/src/facade/collection';
import {
StringWrapper,
isPresent,
isString,
NumberWrapper,
RegExpWrapper
} from 'angular2/src/facade/lang';
import {StringWrapper, isPresent, isString, NumberWrapper} from 'angular2/src/facade/lang';
import {Math} from 'angular2/src/facade/math';
// TODO(jelbourn): Set appropriate aria attributes for grid list elements.
@ -63,7 +57,7 @@ export class MdGridList {
if (value === 'fit') {
this.rowHeightMode = 'fit';
} else if (StringWrapper.contains(value, ':')) {
var ratioParts = StringWrapper.split(value, RegExpWrapper.create(':'));
var ratioParts = value.split(':');
if (ratioParts.length !== 2) {
throw `md-grid-list: invalid ratio given for row-height: "${value}"`;
}

View File

@ -321,7 +321,7 @@ export class PerflogMetric extends Metric {
_markName(index) { return `${_MARK_NAME_PREFIX}${index}`; }
}
var _MICRO_ITERATIONS_REGEX = RegExpWrapper.create('(.+)\\*(\\d+)$');
var _MICRO_ITERATIONS_REGEX = /(.+)\*(\d+)$/g;
var _MAX_RETRY_COUNT = 20;
var _MARK_NAME_PREFIX = 'benchpress';

View File

@ -47,7 +47,7 @@ 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 = RegExpWrapper.create('somePath/someId_\\d+\\.json');
var regExp = /somePath\/someId_\d+\.json/g;
expect(isPresent(RegExpWrapper.firstMatch(regExp, loggedFile['filename']))).toBe(true);
var parsedContent = Json.parse(loggedFile['content']);
expect(parsedContent)

View File

@ -72,7 +72,7 @@ export class DemoUrlResolver extends UrlResolver {
}
}
var _schemeRe = RegExpWrapper.create('^([^:/?#]+:)?');
var _schemeRe = /^([^:/?#]+:)?/g;
// TODO: remove this hack when http://dartbug.com/23128 is fixed
function _isInPubServe(): boolean {