只匹配一个模式一次

编程入门 行业动态 更新时间:2024-10-08 18:33:49
本文介绍了只匹配一个模式一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个字符串

foo-bar-bat.bla

我希望只匹配 foo

我有缺陷的模式同时匹配 foo 和 bar

My flawed pattern matches both foo and bar

\w+(?=-.*\.bla)

如何丢弃 bar?或者甚至更好,我怎么能在 foo 之后停止匹配?

How do I discard bar? Or maybe even better, how could I stop matching stuff after foo?

推荐答案

您可以使用以下模式(只要您的字符串始终按照您所说的方式格式化):

You could use the following pattern (as long as your strings are always formatted the way you said) :

^\w+(?=-.*\.bla)

在 Debuggex 上实时编辑

^ 符号匹配字符串的开头.因此将采用字符串的第一个匹配项.

The ^ sign matches the beginning of the string. And thus will take the very first match of the string.

?= 是为了确保跟随的组未被捕获但存在.

The ?= is meant to make sure the group following is not captured but is present.

更多推荐

只匹配一个模式一次

本文发布于:2023-11-24 00:46:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623354.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!