【问题标题】:Regex: Character set with special characters正则表达式:带有特殊字符的字符集
【发布时间】:2021-07-31 10:28:25
【问题描述】:

正则表达式字符集 ([abc]) 是否可以包含具有特殊含义的字符(例如 $ 表示行尾)?例如,是否可以创建一个匹配/ 或行首^ 的字符集?

我尝试了/[^\/]/g,但它只检查文字^/

注意:我使用的是 JavaScript。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    不,您不能创建自定义的特殊含义,但您可以巧妙地使用正则表达式。

    在执行复杂的正则表达式时,我会测试我正在测试的字符串中是否存在任何这些特殊字符 -

    const str = '¡¢my string <>some content <>between</> fragment</> and other data...'
    const markers = ['\u00A1','\u00A2','\u00A4']; //    ['¡','¢','¤'] you can add others
    const safeMarker = markers.find(marker => str.indexOf(marker) === -1) // ¤ - this is not in the string so I can use it as a marker
    if (safeMarker) {
      const replaced = str.replace(/<\/>/g, safeMarker); // output = 'my string <>some content <>between¤ fragment¤ and other data...'
      // do something with this regex and so on...
      // then replace the string back
    }
    

    这样做的好处是您可以将任意字符组合转换为单个标记,这意味着您可以在否定表达式中使用它,如下所示:

    /<>[^\u00A4]*\u00A4/g  
    

    这相当于(即获取标签之间的内容)

    <>[^</>]*</>
    

    【讨论】:

      猜你喜欢
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 2017-08-14
      相关资源
      最近更新 更多