【问题标题】:REGEX: Finding the correct occurrence order of some given special characters in a string正则表达式:查找字符串中某些给定特殊字符的正确出现顺序
【发布时间】:2013-08-12 07:47:28
【问题描述】:

我想要一个能够找到正确出现顺序的正则表达式

* | . | # | '任何 HTML 元素类型',例如 'p' 或 'div'

喜欢

var regex = //Some regular expression;

var pattern_1 = "*p.class1#id1.class2";
pattern_1.match(regex); // Should print ['*','p','.','#','.']

var pattern_2 = "p.class1#id1.class2"; 
pattern_2.match(regex); //Should print ['p','.','#','.']

var pattern_3 = "p#id1.class1.class2";
pattern_3.match(regex); //Should print ['p','#','.','.']

var pattern_4 = "#id.class1.class2";
pattern_4.match(regex); //should print ['#id','.','.']

var pattern_5 = "*#id.class1.class2";
pattern_5.match(regex); //should print ['*','#','.','.']

我正在与regex = /^\*?[a-zA-Z]*|\#|\./g 碰碰运气,但它不起作用

【问题讨论】:

  • 为了匹配模式的特定部分,您需要使用括号() 进行组捕获。
  • @milkshake 我认为 String.match 函数不需要 ( ),它只是在字符串中搜索匹配正则表达式的匹配项,并将匹配项作为 Array 对象返回。跨度>
  • 对于第 4 种模式,您是否只需要输出中的 ##id
  • @Harry only # 并且都是可选的,即可以重复 0 次或更多次
  • 当然你需要() 来匹配字符串的特定部分:D 然后返回到数组的内容将是整个匹配项,然后是匹配的组。

标签: javascript regex


【解决方案1】:

您最好匹配 #. 以及它们各自的值,然后过滤结果:

 var regex = /\*|([#.]\w+)|(\w+)/g
 matches = pattern_1.match(regex).map(function(x) { return x.match(/^[#.]/) ? x.charAt(0) : x })

或者先去掉id/class名,再匹配:

 matches = pattern_1.replace(/([#.])\w+/g, "$1").match(/[.#*]|\w+/g)

【讨论】:

    【解决方案2】:

    好的,我有:

    /(\*)|(\.)|([a-zA-Z]+)|(#)/g
    

    问题在于,除非您指定所有可以捕获的可能 html 元素,例如 divspan 等,否则它将匹配所有字符串,包括类和 id 名称。

    希望这对您有所帮助。

    Edit live on Debuggex

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      相关资源
      最近更新 更多