gpt4 book ai didi

java - 用于捕获特定数字的正则表达式

转载 作者:行者123 更新时间:2023-12-01 16:44:05 25 4
gpt4 key购买 nike

从下面的日志中,我如何单独 grep '951792' 值

2019 May 22 03:32:17.952296 france1v4 sh[4937]: 190522-03:32:17.951792 [mod=REC, lvl=INFO] [tid=26130] Recording A8602096210405800406L200218680503121519 size is 4145956224 bytes
2019 May 22 03:32:17.952387 france1v4 sh[4937]: 190522-03:32:17.951895 [mod=REC, lvl=INFO] [tid=26130] RecordingInfo = fffocap://0x401e
2019 May 22 03:32:17.952466 france1v4 sh[4937]: 190522-03:32:17.951934 [mod=REC, lvl=INFO] [tid=26130] recording_dvr_from_recording_info:physicalSegmentCount=10

我尝试使用 java split/substring 操作。但代码行数很高。使用正则表达式如何获取“951792”值

输出将是

951792
951895
951934
075041

最佳答案

在这里,我们可能只想简单地使用所需数字旁边的正确边界[mod,并收集第一个捕获组中的数字,可能与此类似:

([0-9]+)\s\[m 

如果我们愿意,我们可以添加更多边界,例如:

(.+?)([0-9]+)\s\[m.+

enter image description here

DEMO

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "(.+?)([0-9]+)\\s\\[m.+";
final String string = "2019 May 22 03:32:17.952296 france1v4 sh[4937]: 190522-03:32:17.951792 [mod=REC, lvl=INFO] [tid=26130] Recording A8602096210405800406L200218680503121519 size is 4145956224 bytes\n"
+ "2019 May 22 03:32:17.952387 france1v4 sh[4937]: 190522-03:32:17.951895 [mod=REC, lvl=INFO] [tid=26130] RecordingInfo = fffocap://0x401e\n"
+ "2019 May 22 03:32:17.952466 france1v4 sh[4937]: 190522-03:32:17.951934 [mod=REC, lvl=INFO] [tid=26130] recording_dvr_from_recording_info:physicalSegmentCount=10 \n";
final String subst = "\\2";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);

演示

const regex = /(.+?)([0-9]+)\s\[m.+/gm;
const str = `2019 May 22 03:32:17.952296 france1v4 sh[4937]: 190522-03:32:17.951792 [mod=REC, lvl=INFO] [tid=26130] Recording A8602096210405800406L200218680503121519 size is 4145956224 bytes
2019 May 22 03:32:17.952387 france1v4 sh[4937]: 190522-03:32:17.951895 [mod=REC, lvl=INFO] [tid=26130] RecordingInfo = fffocap://0x401e
2019 May 22 03:32:17.952466 france1v4 sh[4937]: 190522-03:32:17.951934 [mod=REC, lvl=INFO] [tid=26130] recording_dvr_from_recording_info:physicalSegmentCount=10
`;
const subst = `$2`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

正则表达式

如果不需要此表达式,可以在 regex101.com 中对其进行修改或更改。 .

正则表达式电路

jex.im可视化正则表达式:

enter image description here

关于java - 用于捕获特定数字的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56249034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com