JS正则单行匹配问题

草原上的奶牛 2019-03-04 03:14:24
我使用的正则:
[1-9]\.(.{1})

测试文本:
1.22228.2
5.2
2.我们
0.122

共找到 4 处匹配:
1.2
8.2
5.2
2.我

但我希望的结果是:
1.2
5.2
2.我

也就是单行只需要匹配到第一条即可。
1.22228.2 行字符串中只需要 1.2,8.2不需要。
...全文
183 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
麦草CMS 2019-03-04
  • 打赏
  • 举报
回复
引用 6 楼 草原上的奶牛 的回复:
[quote=引用 3 楼 麦草CMS 的回复:]
/[1-9]+\.(.{1})/m




<textarea id="input">
1.22228.2
5.2
2.我们
0.122
</textarea>

<script>
var regex = /[1-9]+\.(.{1})/gm;
var input = document.getElementById("input").value;
if(regex.test(input)) {
var matches = input.match(regex);
for(var match in matches) {
alert(matches[match]);
}
} else {
alert("没有匹配项!");
}

</script>




出来的结果是:

1.2
2228.2
5.2
2.我

但我要的结果是:
1.2
5.2
2.我[/quote]
<textarea id="input">
afa1.22228.2asdfas
asfasf5.2asgsaf
asfsaf2.4asfad
asdfsa0.122fsdafas
</textarea>

<script>
var reg = /([1-9]+\..{1}).*/g;
var input = document.getElementById("input").value, arr = [], m;
while(m = (reg.exec(input))){
arr.push(m[1]);
alert(m[1]);
}

</script>
麦草CMS 2019-03-04
  • 打赏
  • 举报
回复
引用 7 楼 天际的海浪 的回复:
我是说设置m多行模式,并用^匹配行首

var regex = /^[1-9]\.(.{1})/gm;
var input = document.getElementById("input").value;
var matches = input.match(regex);
if(matches) {
for(var match in matches) {
alert(matches[match]);
}
} else {
alert("没有匹配项!");
}


那就用子匹配
天际的海浪 2019-03-04
  • 打赏
  • 举报
回复
我是说设置m多行模式,并用^匹配行首

var regex = /^[1-9]\.(.{1})/gm;
var input = document.getElementById("input").value;
var matches = input.match(regex);
if(matches) {
  for(var match in matches) {
	alert(matches[match]);
  }
} else {
  alert("没有匹配项!");
}

草原上的奶牛 2019-03-04
  • 打赏
  • 举报
回复
引用 3 楼 麦草CMS 的回复:
/[1-9]+\.(.{1})/m




<textarea id="input">
1.22228.2
5.2
2.我们
0.122
</textarea>

<script>
var regex = /[1-9]+\.(.{1})/gm;
var input = document.getElementById("input").value;
if(regex.test(input)) {
var matches = input.match(regex);
for(var match in matches) {
alert(matches[match]);
}
} else {
alert("没有匹配项!");
}

</script>




出来的结果是:

1.2
2228.2
5.2
2.我

但我要的结果是:
1.2
5.2
2.我
草原上的奶牛 2019-03-04
  • 打赏
  • 举报
回复
引用 4 楼 天际的海浪 的回复:
^[1-9]\.(.{1})
并加m修正符




<textarea id="input">
1.22228.2
5.2
2.我们
0.122
</textarea>

<script>
var regex = /[1-9]+\.(.{1})/gm;
var input = document.getElementById("input").value;
if(regex.test(input)) {
var matches = input.match(regex);
for(var match in matches) {
alert(matches[match]);
}
} else {
alert("没有匹配项!");
}

</script>




出来的结果是:

1.2
2228.2
5.2
2.我

但我要的结果是:
1.2
5.2
2.我
天际的海浪 2019-03-04
  • 打赏
  • 举报
回复
^[1-9]\.(.{1}) 并加m修正符
麦草CMS 2019-03-04
  • 打赏
  • 举报
回复
/[1-9]+\.(.{1})/m
草原上的奶牛 2019-03-04
  • 打赏
  • 举报
回复
引用 1 楼 麦草CMS 的回复:
弄明白了正则表达式中的g修正符了吗?你不加g修正符,怎么可能会匹配出你说的8.2



不加g修正符 只匹配出来 1.2 ,后面的 5.2、2.我 就不匹配了。
麦草CMS 2019-03-04
  • 打赏
  • 举报
回复
弄明白了正则表达式中的g修正符了吗?你不加g修正符,怎么可能会匹配出你说的8.2

87,993

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧