【问题标题】:Not able to match a regexp - Jquery无法匹配正则表达式 - Jquery
【发布时间】:2013-04-11 07:04:59
【问题描述】:

我在 Jquery 中有这段代码 -:

message = '#Usain Bolt #Usain Bolt #Usain Bolt'; message = " "+message+" ";
var type1 = 'Usain Bolt';                                                       
if(message.match(type1))
{ 
  var matchOne = new RegExp(' #'+type1+' ', 'g');  
  var matchTwo = new RegExp('\n#'+type1+' ', 'g'); 

  message = message.replace(matchOne," @"+type1+" ").replace(matchTwo,"\n@"+type1+" ");  
}

生成的消息应该是@Usain Bolt @Usain Bolt @Usain Bolt

但它变成了-:@Usain Bolt #Usain Bolt @Usain Bolt

有什么问题。谢谢你的帮助..

【问题讨论】:

    标签: jquery regex match


    【解决方案1】:

    问题是#Usain Bolts 之间的空格是匹配的一部分。

    " #Usain Bolt #Usain Bolt #Usain Bolt "
     ^-----------^                         first match
                             ^-----------^ second match
                 ^-----------^             no match (a character can only match once)
    

    改为使用单词边界:

    message = '#Usain Bolt #Usain Bolt #Usain Bolt';
    var type1 = 'Usain Bolt';                                                       
    if(message.match(type1))
    { 
      var matchOne = new RegExp('#\\b'+type1+'\\b', 'g');  
      var matchTwo = new RegExp('\n#\\b'+type1+'\\b', 'g'); 
    
      message = message.replace(matchOne," @"+type1).replace(matchTwo,"\n@"+type1);  
    }
    

    【讨论】:

    • @RayZ:它们在单词字符(包括字母、数字和下划线:\w)和非单词字符(或字符串的开头/结尾)之间的位置匹配。
    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 2020-08-22
    • 2018-01-11
    • 2016-01-01
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多