简体   繁体   English

Javascript正则表达式匹配字符串

[英]Javascript Regex Match string

Inputs or spot in the function (always be something along the line): 函数中的输入或点(总是沿线显示):

Washington, T. rush for 3 yards to the MT0 华盛顿T.冲3码到MT0

I want to get the text " to the MT0 " 我想获取文本“ to the MT0

"MT" will be matched with either var homeacrynm or awayacrynm that I will initialize before the function call. “ MT”将与在函数调用之前初始化的var homeacrynmawayacrynm匹配。 Here is what I have tried so far: 到目前为止,这是我尝试过的:

getEndSpotEugene: function(spot)
    {
        var regex = new RegExp("to the +("+homeacrynm+"|"+awayacrynm+")?([0-9]{1,2})","g");
        var matches = spot.match(regex);
        if (matches)
        {
            pos = matches[matches.length-1]
            matches = pos.match(/to the ([A-Z]+)?([0-9]{1,2})/);
            if (!matches[1])
            {
                matches=[pos,"V",50];   
            }
        }
        else
        {
            return -1;  
        }
        var acr = matches[1];
        var yard = matches[2];
        if (acr == homeacrynm) 
            return "H"+yard;
        else
            return "V"+yard;
    },

For example (One simple case): 例如(一种简单情况):

homeacrynm = "MT"
var giveMe = getEndSpotEugene("Washington, T. rush for 3 yards to the MT11")

giveMe should be H11 but its not for some reason. giveMe应该是H11,但出于某种原因而不是。

I am not quite sure where its wrong either. 我也不太清楚哪里错了。 Do you guys see anything that I am missing? 你们看到我想念的东西吗? Thank you! 谢谢!

I made some logs and explicitly declared homeacrynm and awayacrynm like so: 我制作了一些日志,并明确声明了homeacrynm和awayacrynm,如下所示:

  var homeacrynm = "MT";
  var awayacrynm = "H";
  var getEndSpotEugene = function(spot)
  {
      var regex = new RegExp("to the +("+homeacrynm+"|"+awayacrynm+")?([0-9]{1,2})","g");
      console.log(regex);
      var matches = spot.match(regex);
      console.log(matches);
      if (matches)
      {
          pos = matches[matches.length-1]
          matches = pos.match(/to the ([A-Z]+)?([0-9]{1,2})/);
          if (!matches[1])
          {
              matches=[pos,"V",50];   
          }
      }
      else
      {
          return -1;  
      }
      var acr = matches[1];
      var yard = matches[2];
      console.log(acr);
      console.log(yard);          
      if (acr == homeacrynm) 
          return "H"+yard;
      else
          return "V"+yard;
  }

Strangely, I get H11 as you expect! 奇怪的是,我得到了您期望的H11! What are you getting? 你得到什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM