我有以下代码:
const regEx = /\[~(\d|-|[a-f]){32,36}\]/;
var str = "How [~75e0a072-6464-4e00-8229-a3b6b799a673] to
[~457713c4-a752-4eed-b835-28f7ef74b682] also [~57713c4-a752-4eed-b835-28f7ef74b682] you?";
var res = str.split(regEx);
res是:
How ,3, to ,2, also ,2, you?
我希望:
How ,[~75e0a072-6464-4e00-8229-a3b6b799a673], to ,[~457713c4-a752-4eed-b835-28f7ef74b682], also ,[~57713c4-a752-4eed-b835-28f7ef74b682], you?
这是一段代码段 https://jsfiddle.net/3k9g117d/
答案 0 :(得分:1)
问题是已知问题,repeated capturing group仅保留组内存缓冲区中的最后匹配值。
(\d|-|[a-f])
组应该重写为[-\da-f]
,限制量词应该应用于它,捕获括号应该包裹整个模式,
const regEx = /(\[~[-\da-f]{32,36}\])/;
参见JS演示:
// find elements
var banner = $("#banner-message")
var button = $("button")
var res = [];
function myFunction() {
const regEx = /(\[~[-\da-f]{32,36}\])/;
var str = "How [~75e0a072-6464-4e00-8229-a3b6b799a673] to [~457713c4-a752-4eed-b835-28f7ef74b682] also [~57713c4-a752-4eed-b835-28f7ef74b682] you?";
var res = str.split(regEx);
document.getElementById("demo").innerHTML = res;
}
// handle click and add class
button.on("click", myFunction)
document.getElementById("demo").innerHTML = res;
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
<button>Test regEx</button>
<p id="demo"></p>
</div>