使用javascript中的正则表达式无法获得正确的输出

时间:2018-11-22 03:27:39

标签: javascript html

我有一句话,我需要将其提取出来并获得正确的输出。

Welcome to project, are you a here(1. new user one, 2. test user two, 3. minor Accident one or 4. Major Accident)

我现在使用正则表达式获取输出:-

Welcome to project, are you a here
1. new user
2. test user
3. minor Accident or
4. Major

我应该使用正则表达式按句子获取输出:-

Welcome to project, are you a here
1. new user one
2. test user two
3. minor Accident one
4. Major Accident

这是下面的代码,在我使用过的plnker中进行了更新,由于我对正则表达式的了解不多,所以我没有得到解决方案。

$(document).ready(function() {
  regex = /.+\(|\d. [\w\s]+ /g;
  maintext = "Welcome to project, are you a here(1. new user one, 2. test user two, 3. minor Accident one or 4. Major Accident)";
  matches = maintext.match(regex);
  text_split0 = matches[0].slice(0, -1);
  text_split1 = matches[1];
  text_split2 = matches[2];
  text_split3 = matches[3];
  text_split4 = matches[4];
  console.log(text_split0);
  console.log(text_split1);
  console.log(text_split2);
  console.log(text_split3);
  console.log(text_split4);
  $(".messages").append('<li>' + text_split0 + '</li><li>' + text_split1 + '</li><li>' + text_split2 + '</li><li>' + text_split3 + '</li><li>' + text_split4 + '</li>');
  // $("li:contains('undefined')").remove()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="messages">
</ul>

1 个答案:

答案 0 :(得分:0)

而不是创建一个独角兽正则表达式;分两步完成。将正则表达式简化为仅查找数字。因此,您正在与此匹配:

https://regex101.com/r/BXf1IM/1

const p1button = document
    .querySelector('#p1')
    .addEventListener('click', scoreUp);
const p2button = document
    .querySelector('#p2')
    .addEventListener('click', scoreUp);

let p1 = document.querySelector('#p1score');
let p2 = document.querySelector('#p2score');
let p1score = p1.textContent;
let p2score = p2.textContent;

function scoreUp(e) {
    if (e.target.textContent === 'Player 1') {
        p1.textContent = p1score++;
        console.log(p1.textContent);
    } else {
        p2.textContent = p2score++;
        console.log(p2.textContent);
    }
}

然后,用数字将字符串分割会更容易。

"1. new user one, 2. test user two, 3. minor Accident one or 4. Major Accident"

然后,您可以遍历这些内容,将其添加到订单列表中。

list.split(/([\d]. )/g)

您需要清理第三项上的“或”。

完整脚本:

<ol class="messages">
    <li>new user one</li>
    <li>test user two</li>
    <li>minor Accident one or </li>
    <li>Major Accident</li>
</ol>