其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

如何在Go中检测单个字符串中的正则表达式的所有匹配项

GG网络技术分享 2025-03-18 16:14 2


问题描述:

I am attempting to build a regex to detect a unix timestamp like pattern in a string. However, some strings contain multiple \"unix time\" like patterns and go\'s regex only detects the first instance of such pattern.

My current regex:

utcRegex, _ := regexp.Compile(^.*\\[(\\d{7,})\\].*)

utcCheck := utcRegex.FindStringSubmatch(string)

utc := utcCheck[1]

Here are some example strings:

Regex works fine with these type of strings

\"Nov 6 11:21:34 [14039] : [1541532094] [DEBUG] FOO BAR\"

The regex properly detects the 1541532094

Regex does not fulfull what I want

\"08-13 11:46:56.379 24980 24980 D SDK: [1565711216] [DEBUG] [15657110953902503] [FOO BAR ]\"

The regex only detects 15657110953902503 but not 1565711216. I am only interested in 1565711216. The regex only finds 15657110953902503

Is there an update I can make to my go regex that will detect both of these and then select the first/second instance of this pattern?

图片转代码服务由CSDN问答提供

感谢您的意见,我们尽快改进~

功能建议

我正在尝试构建一个正则表达式来检测字符串中的模式之类的unix时间戳。 但是,某些字符串包含多个“ unix time”(例如模式),而go的正则表达式仅检测到该模式的第一个实例。</ p>

我当前的正则表达式:</ p>

utcRegex,_:= regexp.Compile( ^。* \\ [(\\ d {7,})\\]。* </ code>)</ p>

utcCheck:= utcRegex。 FindStringSubmatch(string)</ p>

utc:= utcCheck [1] </ p>

以下是一些示例字符串:</ p>

正则表达式可以在这些类型的字符串上正常工作</ strong> </ p>

“ 11月6日11:21:34 [14039]:[1541532094] [DEBUG] FOO BAR” </ p >

正则表达式正确检测到1541532094 </ p>

正则表达式无法满足我的需求</ strong> </ p>

“ 08-13 11:46:56.379 24980 24980 D SDK:[1565711216] [DEBUG] [15657110953902503] [FOO BAR]” </ p>

正则表达式仅检测到15657110953902503,但未检测到1565711216。我是 仅对1565711216感兴趣。此正则表达式仅找到15657110953902503 </ p>

我可以对go regex进行更新,以检测这两种情况,然后选择此模式的第一个/第二个实例 ?</ p>

</ div>

网友观点:

Your regex is too rigid, try:

\\[(\\d{7,})\\]

and $1 will contain the matches.

https://regex101.com/r/XoEx56/1

python通过正则表达式实现字符(串)匹配

一、什么是正则表达式

正则表达式,又称规则表达式,用来检索、替换那些符合某个模式(规则)的文本。模式,是正则表达式最基本的元素,它们是一组描述字符串特征的字符。模式可以很简单,由普通的字符串组成,也可以非常复杂,往往用特殊的字符表示一个范围内的字符、重复出现,或表示上下文。

1、简单的模式:由简单的字符串组成

标签:

提交需求或反馈

Demand feedback