首页 > 解决方案 > SyntaxError:无效的正则表达式:/INFO/:新 RegExp 处的未终止字符类()

问题描述

代码:

it.only('should display logs in color when using chalk', () => {
    // Setup.
    const uuid = uuidv4();
    const messages = [
        // prettier-ignore
        [`${uuid}_chalk_info`, '\[37mINFO\[39m'],
        [`${uuid}_chalk_debug`, '\[36mDEBUG\[39m'],
        [`${uuid}_chalk_trace`, '\[32mTRACE\[39m']
    ];
    testLog(messages[0][1]);
    const log = languramaLog({ ...defaultTerminalConfiguration, level: 'trace', chalk });
    const mock = jest.spyOn(process.stdout, 'write').mockImplementation(() => {});
    // Test.
    log.info(messages[0][0]);
    log.debug(messages[1][0]);
    log.trace(messages[2][0]);
    // Assert.
    expect(mock).toHaveBeenCalledTimes(3);
    expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[0][1]));
    expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[1][1]));
    expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[2][1]));
});

错误:

SyntaxError: Invalid regular expression: /INFO/: Unterminated character class
    at new RegExp (<anonymous>)

  359 |             // Assert.
  360 |             expect(mock).toHaveBeenCalledTimes(3);
> 361 |             expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[0][1]));
      |                                                       ^
  362 |             expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[1][1]));
  363 |             expect(mock).toHaveBeenCalledWith(jasmine.stringMatching(messages[2][1]));
  364 |         });

所以我使用这个包chalk为一些我想测试的日志创建颜色,以确保日志被打印到终端。但是茉莉花中的正则表达式似乎在抱怨,有什么想法吗?

以下工作正常:

const log = new RegExp(/\[37mINFO\[39m/);

const result = log.test('[90m2020-05-02 23:54:51 UTC+2[39m   [37mINFO[39m 2df268af-af1f-42f0-b098-d52fb0123d95_chalk_info [90m/home/karl/dev/langurama/log/test/index.node.spec.js:358:17[39m');

console.log(result); // true

标签: regexjasmine

解决方案


在从字符串文字构建的 Regexen 中,您必须将转义字符加倍:一个实例是\在字符串文字中转义以获得正则表达式的正则表达式转义字符。

所以你的模式看起来像:

 \\[37mINFO\\[39m

测试用例:

let re_s
  , re_d
  , re_s_nostring
  , re_d_nostring
  ;

try { re_s = new RegExp ( '\[37mINFO\[39m', 'g' );   } catch (e) { console.log('re_s: constructor fails.\n' ); } // This always fails.
try { re_d = new RegExp ( '\\[37mINFO\\[39m', 'g' ); } catch (e) { console.log('re_d: constructor fails.\n' ); }
try { re_s_nostring = /\[37mINFO\[39m/g;             } catch (e) { console.log('re_s_nostring: constructor fails.\n' ); }
// Syntactically wrong, won't compile into bytecode
// re_d_nostring = /\\[37mINFO\\[39m/g;

if (re_d) { console.log ( re_d.test("[37mINFO[39m") ? "re_d matches" : "re_d does not match" ); } 
if (re_s_nostring) { console.log ( re_s_nostring.test("[37mINFO[39m") ? "re_s_nostring matches" : "re_s_nostring does not match" ); }


推荐阅读