【问题标题】:Use regex to capture characters between colon and comma使用正则表达式捕获冒号和逗号之间的字符
【发布时间】:2019-08-12 02:16:21
【问题描述】:

EsLint 在捕获一个已经输出天气的字符串时输出错误。

字符串示例:

let example = 'Current Conditions: Mostly Cloudy, 16.5°C';

目标是捕获描述天气状况的字符串“多云”。

输出错误的正则表达式:

let wecur_tcond = $(example).text(/\:(.*?)\,/g,"");
console.log(wecur_tcond);

以及错误输出:

Unnecessary escape character: \:  no-useless-escape
Unnecessary escape character: \,  no-useless-escape

编辑:没有反斜杠来转义字符,控制台输出:

Uncaught Error: Syntax error, unrecognized expression:Current Conditions: Mostly Cloudy, 16.5°C

【问题讨论】:

  • 您是否对错误信息感到困惑?它表示您不需要冒号和逗号之前的反斜杠。照你说的做。
  • 按照明显的说明更新了更多错误代码
  • 实际上,你为什么要在字符串上使用 jQuery 语法?你应该这样做:example.replace(/:(.*?),/g,"")
  • @canacast The goal is to capture the string to describe the weather condition, 'Mostly cloudy'. 但在您的代码中,您将替换 Mostly cloudy 而不是捕获它
  • @canacast 你想得到Mostly cloudy 作为输出或除Mostly cloudy 之外的所有其他内容?

标签: javascript jquery regex eslint


【解决方案1】:

:, 不是特殊字符,因此您不需要转义,(: 在捕获组中使用时是特殊字符,紧跟在 ?i.e (?:) 之后)

你也不需要(),因为你没有在任何地方使用捕获组的引用,

还可以将正则表达式改进为[^,]+ 而不是.*?

let example = 'Current Conditions: Mostly Cloudy, 16.5°C';
let wecur_tcond = example.replace(/:[^,]+,/g,"");
console.log(wecur_tcond);

目标是捕获描述天气状况的字符串, “多云”

let example = 'Current Conditions: Mostly Cloudy, 16.5°C';
let wecur_tcond = example.match(/:[^,]+/)[0].replace(/^:\s*/,'')
console.log(wecur_tcond);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多