regex 正则表达式查找10或100,1000.不起作用

ubbxdtey  于 2023-10-22  发布在  其他
关注(0)|答案(2)|浏览(111)

我创建了正则表达式/(10?|10{2,})/g求1,10或100,1000.但是下面的代码没有返回预期的结果。我不知道我哪里做错了,请帮帮我!

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Do a global search for a "1", followed by zero or one "0" characters:</p>

<p id="demo"></p>

<script>
let text = "1, 10, 100 or 1000?";
let result = text.match(/(10?|10{2,})/g);
//should return 1,10,100,1000 but instead return 1,10,10,10
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>
k2arahey

k2arahey1#

我会补充。
搜索子字符串:

let text = "1, 10, 100 or 1000 (3100, 10000, 1000000)?";
let result = text.match(/10{1,3}/g);

输出量:

10,100,1000,100,1000,1000

仅在模式上搜索单词:

let text = "1, 10, 100 or 1000 (3100, 10000, 1000000)?";
let result = text.match(/\b10{1,3}\b/g);

输出量:

10,100,1000

仅搜索模式1和更多零的单词:

let text = "1, 10, 100 or 1000 (3100, 10000, 1000000)?";
let result = text.match(/\b10{1,}\b/g);

输出量:

10,100,1000,10000,1000000

查找以1个或多个零结尾的单词:

let text = "1, 10, 100 or 1000 (3100, 10000, 1000000)?";
let result = text.match(/\b\w*10{1,}\b/g);

输出量:

10,100,1000,3100,10000,1000000

查找仅以1个或多个零结尾的单词:

let text = "1, 10, 100 or 1000 (3100, 10000, 1000000)?";
let result = text.match(/\b\w+10{1,}\b/g);

输出量:

3100
z9ju0rcb

z9ju0rcb2#

问题是10?将匹配字符串中的所有1101001000,由于这是交替中的第一个元素,正则表达式引擎在匹配时停止(因此最长匹配是10)。你可以通过交换交替来解决这个问题,这样最长的匹配是第一个:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Do a global search for a "1", followed by zero or one "0" characters:</p>

<p id="demo"></p>

<script>
let text = "1, 10, 100 or 1000?";
let result = text.match(/10{2,}|10?/g);
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>

但更好的是,只需将正则表达式简化为10*1后跟0个或多个0 s):

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Do a global search for a "1", followed by zero or one "0" characters:</p>

<p id="demo"></p>

<script>
let text = "1, 10, 100 or 1000?";
let result = text.match(/10*/g);
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>

请注意,这些正则表达式也将匹配21125107。如果你不想这样做,在正则表达式的两端添加一个\b(单词边界)。见下文

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Do a global search for a "1", followed by zero or one "0" characters:</p>

<p id="demo"></p>

<script>
let text = "1, 10, 100 or 1000? But what about 12, 21 and 5107?";
let result = text.match(/\b10*\b/g);
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>

还要注意的是,在正则表达式中不需要捕获组(...),因为你只对整个匹配感兴趣。

相关问题