360フロントエンドスタープロジェクト-正規表現の作成と使用(Wang Feng)

1.正規表現の作成と使用

1.1正規表現を作成する

  • 正規表現リテラルを使用して
    const reg = /[a-z]\d+[a-z]/i;
    / /、正規表現、[a-z]文字、\d数字の内容含め、+\d)の前に1回以上繰り返し、i修飾子を示し、大文字と小文字を無視します

    • 利点:シンプルで便利で、二次エスケープを考慮する必要がない
    • 短所:サブコンテンツは再利用できません。規則性が長すぎると、読みにくくなります。
  • RegExpコンストラクターを使用する

    const alphabet = '[a-z]';
    const reg = new RegExp(`${alphabet}\\d+${alphabet}`, 'i');
    
    • 利点:サブコンテンツを再利用でき、サブコンテンツの粒度を制御することで可読性を向上できます。
    • 短所:二次エスケープの問題はバグを引き起こしやすい
      const reg = new RegExp(`\d+`);
      reg.test('1'); // false
      reg.test('ddd'); // true
      

1.2正規表現を使用する

  • RegExp.prototype.test()

    const reg = /[a-z]\d+[a-z]/i;
    reg.test('a1a'); // true
    reg.test('1a1'); // false
    reg.test(Symbol('a1a')); // TypeError
    

    入力:入力文字列が必要です。入力が文字列型ではない場合、型変換が試行されます。変換が失敗した場合、TypeErrorが
    出力されます: trueまたはfalse、一致の成功または失敗を示します

  • RegExp.prototype.source(コンテンツ)およびRegExp.prototype.flags(修飾子と昇順でのソート)

    const reg = /[a-z]\d+[a-z]/ig;
    reg.source; // "[a-z]\d+[a-z]"
    reg.flags; // "gi"
    
  • RegExp.prototype.exec()とString.prototype.match()

    const reg = /[a-z]\d+[a-z]/i;
    reg.exec('a1a'); // ["a1a", index: 0, input: "a1a", groups: undefined]
    reg.exec('1a1'); // null
    'a1a'.match(reg); // ["a1a", index: 0, input: "a1a", groups: undefined]
    '1a1'.match(reg); // null
    

    入力: RegExp.prototype.execは文字列の入力を必要とし、文字列
    以外のタイプを検出すると変換を試みます; String.prototype.matchは正規表現の入力を必要とし、他のタイプを検出すると、最初に文字列への変換を試み、次に文字列を次のように使用しますソースは正規表現を作成します

    出力:一致成功、一致結果を返す、一致失敗、nullを返す

String.prototype.matchによって返されるデータ形式は固定されていないため、ほとんどの場合、RegExp.prototype.execを使用することをお勧めします

  • RegExp.prototype.lastIndex
    注: lastIndex自体はリセットされず、最後の一致が失敗した場合にのみ0にリセットされるため、同じ正規表現を繰り返し使用する必要がある場合は、毎回新しい文字を一致させてください文字列の前のlastIndexをリセットしてください!
  • String.prototype.replace()、String.prototype.search()、String.prototype.split()

2. 3つのアプリケーションシナリオ

2.1シナリオ1:通常および数値

数値判断プロセス:

  • /[0-9]+/ :不完全な一致(数字が含まれている場合)
  • /^\d+$/:符号付き値と小数を一致させることはできません
  • /^[+-]?\d+(\.\d+)?$/:整数部(.123)がない小数には一致しません
  • /^[+-]?(?:\d*\.)?\d+$/:小数部(2.)および科学表記(-2.e + 4)がない値と一致させることはできません

完全な数値的規則性:
完全な数値トークン

  • /^[+-]?(?:\d+\.?|\d*\.\d+)(?: e[+-]?\d+)?$/i

正規化を使用して値を処理します。

  • 数値解析

    const reg = const reg = /[+-]?(?:\d*\.)?\d+(?:e[+-]?\d+)?(?=px|\s|$)/gi;
    
    function execNumberList(str) {
        reg.lastIndex = 0;
        let exec = reg.exec(str);
        const result = [];
        while (exec) {
            result.push(parseFloat(exec[0]));
            exec = reg.exec(str);
        }
        return result;
    }
    
    console.log(execNumberList('1.0px .2px -3px +4e1px')); // [1, 0.2, -3, 40]
    console.log(execNumberList('+1.0px -0.2px 3e-1px')); // [1, -0.2, 0.3]
    console.log(execNumberList('1px 0')); // [1, 0]
    console.log(execNumberList('-1e+1px')); // [-10]
    
  • 通貨フォーマットの値:つまり、カンマが1000分の1に追加されます。

    const reg = /(\d)(?=(\d{3})+(,|$))/g;
    function formatCurrency(str) {
       return str.replace(reg, '$1,');
    }
    
    console.log(formatCurrency('1')); // 1
    console.log(formatCurrency('123')); // 123
    console.log(formatCurrency('12345678')); // 12,345,678
    

2.2シーン2:規則性と色

色を表す方法の数:

  • 16進表記

    color: #rrggbb;
    color: #rgb;
    color: #rrggbbaa;
    color: #rgba;
    
    const hex = '[0-9a-fA-F]';
    const reg = new RegExp(`^(?:#${hex}{6}|#${hex}{8}|#${hex}{3,4})$`);
    
  • rgb / rgba表記

    color: rgb(r, g, b);
    color: rgb(r%, g%, b%);
    color: rgba(r, g, b, a);
    color: rgba(r%, g%, b%, a);
    color: rgba(r, g, b, a%);
    color: rgba(r%, g%, b%, a%);
    
    const num = '[+-]?(?:\\d*\\.)?\\d+(?:e[+-]?\\d+)?';
    const comma = '\\s*,\\s*';
    const reg = new RegExp(`rgba?\\(\\s*${num}(%?)(?:${comma}${num}\\1){2}(?:${comma}${num}%?)?\\s*\\)`);
    
  • その他の

    /* hsl & hsla */
    color: hsl(h, s%, l%);
    color: hsla(h, s%, l%, a);
    color: hsla(h, s%, l%, a%);
    
    /* keywords */
    color: red;
    color: blue;
    /* …… */
    

通常の処理色を使用:

  • 16進数の色の最適化
    const hex = '[0-9a-z]';
    const hexReg = new RegExp(`^#(?<r>${hex})\\k<r>(?<g>${hex})\\k<g>(?<b>${hex})\\k<b>(?<a>${hex}?)\\k<a>$`, 'i');
    function shortenColor(str) {
        return str.replace(hexReg, '#$<r>$<g>$<b>$<a>');
    }
    
    console.log(shortenColor('#336600')); // '#360'
    console.log(shortenColor('#19b955')); // '#19b955'
    console.log(shortenColor('#33660000')); // '#3600'
    

2.3シナリオ3:通常およびURL

完全なURL仕様
URLを解析します。

const protocol = '(?<protocol>https?:)';
const host = '(?<host>(?<hostname>[^/#?:]+)(?::(?<port>\\d+))?)';
const path = '(?<pathname>(?:\\/[^/#?]+)*\\/?)';
const search = '(?<search>(?:\\?[^#]*)?)';
const hash = '(?<hash>(?:#.*)?)';
const reg = new RegExp(`^${protocol}\/\/${host}${path}${search}${hash}$`);
function execURL(url) {
    const result = reg.exec(url);
    if (result) {
        result.groups.port = result.groups.port || '';
        return result.groups;
    }
    return {
        protocol: '', host: '', hostname: '', port: '',
        pathname: '', search: '', hash: '',
    };
}

console.log(execURL('https://www.360.cn'));
console.log(execURL('http://localhost:8080/?#'));
console.log(execURL('https://image.so.com/view?q=360&src=srp#id=9e17bd&sn=0'));
console.log(execURL('this is not a url'));

console.log(execURL('https://www.360.cn'));
{
  protocol: 'http:',
  host: 'www.360.cn',
  hostname: 'www.360.cn',
  port: '',
  pathname: '',
  search: '',
  hash: ''
}
console.log(execURL('http://localhost:8080/?#'));
{
  protocol: 'http:',
  host: 'localhost:8080',
  hostname: 'localhost',
  port: '8080',
  pathname: '/',
  search: '?',
  hash: '#'
}
console.log(execURL('https://image.so.com/view?q=360&src=srp#id=9e17bd&sn=0'));
{
  protocol: 'https:',
  host: 'image.so.com',
  hostname: 'image.so.com',
  port: '',
  pathname: '/view',
  search: '?q=360&src=srp',
  hash: '#id=9e17bd&sn=0'
}
console.log(execURL('this is not a url'));
{
  protocol: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '',
  search: '',
  hash: ''
}

レギュラーを使用して検索とハッシュを解析します。

function execUrlParams(str) {
    str = str.replace(/^[#?&]/, '');
    const result = {};
    if (!str) {
        return result;
    }
    const reg = /(?:^|&)([^&=]*)=?([^&]*?)(?=&|$)/y;
    let exec = reg.exec(str);
    while (exec) {
        result[exec[1]] = exec[2];
        exec = reg.exec(str);
    }
    return result;
}

console.log(execUrlParams('#')); // { }
console.log(execUrlParams('##')); // { '#': '' }
console.log(execUrlParams('?q=360&src=srp')); // { q: '360', src: 'srp' }
console.log(execUrlParams('test=a=b=c&&==&a=')); // { test: 'a=b=c', '': '=', a: '' }

3.まとめ

正規表現を使用するには?

  • 明確な需要
  • 包括的な検討
  • 繰り返しテスト
元の記事を8件公開 Likes0 訪問数48

おすすめ

転載: blog.csdn.net/liu_ye96/article/details/105427012