匹配特定单词中的字母和数字

时间:2018-04-21 15:48:08

标签: javascript regex

我一直试图匹配特定单词中的字符串。 例如:

A B~A C D A2D2B(A2)

如果字母旁边有数字,我的jquery代码应该工作,输出必须大写。我希望结果只匹配每个单词的单个字母,但是如果有一个数字,则取该数字并将其与旁边的字母匹配。

现在我的当前输出是:

  

干草蜂〜干草见A2D2B(HAY)

结果必须是:

  

干草蜂〜干草见天HAY DAY BEE(HAY)

我的Javascript代码:

 $("button.btn#converter").click(function() {

   var original = $('span[style="color: #660000;"]').text();

   var first = ['A', 'B', 'C', 'D', 'A2','B2','C2','D2'];
   var second = ['hay', 'bee', 'see', 'day', 'HAY', 'BAY', 'SEE','DAY'];

   var result = $.map(first, function(v) {
     return new RegExp('\\b'+v+'\\b', 'g');
   });


   $('span[style="color: #660000;"]').text(function(i, val) {
     $.each(first, function(i) {
       val = val.replace(result[i], second[i]);
     });
     return val;
   });


 });

这里是jsfiddle:https://jsfiddle.net/akoni/knp1fcwj/

2 个答案:

答案 0 :(得分:0)

当前方法的问题是首先替换单个字符元素。类似A2的字符串与AA2元素匹配,并且由于A首先出现,您最终会得到hay2

要解决此问题,您需要先替换包含最多字符的元素(包含其他元素)。

以下是一个例子:

 $("button.btn#converter").click(function() {
   var first = ['A2','B2','C2','D2', 'A', 'B', 'C', 'D'];
   var second = ['HAY', 'BAY', 'SEE','DAY', 'hay', 'bee', 'see', 'day'];
   
   // Create a single regex that contains all the elements as groups
   var pattern = new RegExp(first.map(function(v){
   		return "(" + v + ")";
   }).join("|"), "g");

   $('span[style="color: #660000;"]').text(function(i, val) {
     return val.replace(pattern, function(g){
     		return second[first.indexOf(g)];
     });
   });
 });
.btn {
  background: #3498db;
  background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
  background-image: -moz-linear-gradient(top, #3498db, #2980b9);
  background-image: -ms-linear-gradient(top, #3498db, #2980b9);
  background-image: -o-linear-gradient(top, #3498db, #2980b9);
  background-image: linear-gradient(to bottom, #3498db, #2980b9);
  -webkit-border-radius: 28;
  -moz-border-radius: 28;
  border-radius: 28px;
  font-family: Arial;
  color: #ffffff;
  font-size: 15px;
  padding: 10px 20px 10px 20px;
  text-decoration: none;
}

.btn:hover {
  background: #3cb0fd;
  background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
  background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
  text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span style="color: #660000;">A&nbsp; &nbsp; B~A&nbsp; &nbsp; &nbsp;C&nbsp; &nbsp; &nbsp;D</span>
<br />
<span style="font-family: &quot;georgia&quot; , &quot;times new roman&quot; , serif;">Sample Text Here<br /><span style="color: #660000;">A2D2B&nbsp; &nbsp; &nbsp; C&nbsp; &nbsp; &nbsp; (A2)</span></span><br />
<span style="font-family: &quot;georgia&quot; , &quot;times new roman&quot; , serif;">Sample Text Here</span>
<br/>
<br/>
<button class="btn" id="converter">Magic</button>

答案 1 :(得分:0)

由于你的输出有一些没有输入的空格,我为它添加了一些检查逻辑。

根据评论,它现在可以转换回来。

修改:添加了新案例B(wow)。我更改了正则表达式以捕获转换或未转换的文本和括号的所有情况以及空间检测逻辑。

var first = ['A', 'B', 'C', 'D', 'A2', 'B2', 'C2', 'D2'];
var second = ['hay', 'bee', 'see', 'day', 'HAY', 'BAY', 'SEE', 'DAY'];
var $span = $('span[style="color: #660000;"]')
var isConverted = false
var spaceArray = []
for(var i=0;i<$span.length;i++){
  spaceArray.push([])
}

$("button.btn#converter").click(function() {
  $.each($span, function(spanIndex, ele) {
    var text = $(ele).text()
    var reg = isConverted ? /([a-zA-Z]+\d?|\W)/g : /([a-zA-Z]{1}\d?|\W)/g
    var textArray = []
    var spaceIndex = 0;
    var convertIndex = 0;
    
    // find all matches as an array
    var matches = text.match(reg)
    $.each(matches, (arrayIndex, t) => {
      var _first = isConverted ? second : first
      var _second = isConverted ? first : second

      // find the index of match text in first array
      var i = _first.indexOf(t)
  
      // if captured char is not in both array
      if(i == -1){
        textArray.push(t)
        return;
      }

      // check if the next char is non-character
       var char = text[text.indexOf(t) + t.length] || " "

      var replace = _second[i]   
      var index = text.indexOf(t)
      
      // if next char is not a non-character, then add a space after it
      if(isConverted){
        if(spaceArray[spanIndex].length>0){
          if(spaceArray[spanIndex][0] == convertIndex){
            matches.splice(arrayIndex,1)
            spaceArray[spanIndex].shift()
          }
        }
      }
      else{
        if (!/\W/.test(char)) {
          replace = replace + " "
          spaceArray[spanIndex].push(convertIndex)
        }
      }
      
      text = text.substr(index+t.length, text.length)
      
      t = t.replace(t, replace)
      convertIndex++;
      textArray.push(t)
    })
    text = textArray.join('')
    $(ele).text(text)
  })
  $('#converter').text(isConverted ? 'Magic' : 'Original')
  isConverted = !isConverted
});
.btn {
  background: #3498db;
  background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
  background-image: -moz-linear-gradient(top, #3498db, #2980b9);
  background-image: -ms-linear-gradient(top, #3498db, #2980b9);
  background-image: -o-linear-gradient(top, #3498db, #2980b9);
  background-image: linear-gradient(to bottom, #3498db, #2980b9);
  -webkit-border-radius: 28;
  -moz-border-radius: 28;
  border-radius: 28px;
  font-family: Arial;
  color: #ffffff;
  font-size: 15px;
  padding: 10px 20px 10px 20px;
  text-decoration: none;
}

.btn:hover {
  background: #3cb0fd;
  background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
  background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
  text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span style="color: #660000;">A&nbsp; &nbsp; B~A2D2&nbsp; &nbsp; &nbsp;C&nbsp; &nbsp; &nbsp;D</span>
<br />
<span style="font-family: &quot;georgia&quot; , &quot;times new roman&quot; , serif;">Sample Text Here<br /><span style="color: #660000;">A2D2B&nbsp; &nbsp; &nbsp; C&nbsp; &nbsp; &nbsp; (A2)</span></span><br />
<span style="font-family: &quot;georgia&quot; , &quot;times new roman&quot; , serif;">Sample Text Here<br /><span style="color: #660000;">B~A2D2</span></span><br />
<span style="color: #660000;">C~DC</span><br />
<span style="color: #660000;">B(wow)</span><br />

<br/>
<button class="btn" id="converter">Magic</button>