匹配可选的String正则表达式(Matching optional String regex)

编程入门 行业动态 更新时间:2024-10-27 09:36:48
匹配可选的String正则表达式(Matching optional String regex)

我必须为我的小问题找到解决方案: - /。

我有一条消息,例如

状态:好的

要么

状态:ERR |下一条消息

是否可以为“状态”创建正则表达式+可选的消息如果存在?

非常感谢

刘若英

i have to find a solution for my little Problem :-/.

I have a message eg

Status: OK

or

Status: ERR|next Message

is it possible to create a regex for "Status" + optional the Message if exists ?

Thanks a lot

Rene

最满意答案

你可以使用这样的东西:

/^Status:\s*([A-Z]+)(?:\|([^$]*))?$/

这匹配所有数据,并返回OK或ERR作为第一个元素,只返回消息作为第二个元素。

附加信息 :(?:表示法(在\ |之前),是一个“隐藏”分组。即组,但不提取。

You can use something like this:

/^Status:\s*([A-Z]+)(?:\|([^$]*))?$/

This matches all the data, and returns OK or ERR as the first element, and only the message as the second element.

Additional information: The (?: notation (before the \|), is a "hidden" grouping. That is, group but don't fetch.

更多推荐

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

发布评论

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

>www.elefans.com

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