我有各种不同信息的字符串,但它们都有一个共同特征:它们包含请求者的用户名,后面有括号。 类似的东西: "... 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.
更多推荐
发布评论