正则表达式在括号前得到正确的词(regex for getting word right before brackets)

编程入门 行业动态 更新时间:2024-10-22 22:50:41
正则表达式在括号前得到正确的词(regex for getting word right before brackets)

我有各种不同信息的字符串,但它们都有一个共同特征:它们包含请求者的用户名,后面有括号。 类似的东西: "... paul [55] ..."我试图写一个能够在[dd]之前提取单词的正则表达式 这就是我到目前为止: "/(?P<user>\w+)\s\[\d\d\]/"但这仅在字符串以用户开头时有效,例如"paul [55] has logged in"但在案件中不起作用"user paul [55] has logged off" 我错过了什么?

I have various strings with different information but they all share one common characteristic: they contain the username of the requester with brackets right after it. Something like: "... paul [55] ..." I am trying to write a regex that is able to extract the word right before the [dd] This is what I have so far: "/(?P<user>\w+)\s\[\d\d\]/" but this only works if the string starts with the user, such as "paul [55] has logged in" but it wouldn't work in the case, "user paul [55] has logged off" What am I missing?

最满意答案

尝试使用正向前瞻断言

(\w+)(?=\s?\[\d\d\])

仅当该表达式后跟可选空格和括在方括号中的两位十进制数时,此表达式才匹配一个或多个单词字符。

Try using positive lookahead assertion:

(\w+)(?=\s?\[\d\d\])

This expression matches one or more word characters only if it is followed by an optional space and a double-digit decimal number enclosed in square brackets.

更多推荐

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

发布评论

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

>www.elefans.com

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