简体   繁体   English

如何使用正则表达式仅提取双引号、单引号之间的数字或不提取数字

[英]How extract only numbers between double quotes, simple quotes or without them using regex

I have a Java code that processes events in real time, from which it extracts information using regex, recently it fails, after hours of debugging, I find that this value can arrive in the 3 ways that I leave here:我有一个实时处理事件的 Java 代码,它使用正则表达式从中提取信息,最近它失败了,经过数小时的调试,我发现这个值可以通过我离开这里的 3 种方式到达:

{"eventId":"25","started":"2022-07-29T18:37:38.717Z","finished":"2022-07-29T18:37:38.717Z","duration":0,"sessionId":"xxxx","personId":"1111111","status":"ok"}
{"eventId":'25',"started":"2022-07-29T18:37:38.717Z","finished":"2022-07-29T18:37:38.717Z","duration":0,"sessionId":"xxxx","personId":"1111111","status":"ok"}
{"eventId":25,"started":"2022-07-29T18:37:38.717Z","finished":"2022-07-29T18:37:38.717Z","duration":0,"sessionId":"xxxx","personId":"1111111","status":"ok"}

I have tried without success to modify the current regex that extracts the information, to extracts the eventId number 25 in any of the three cases:我尝试修改提取信息的当前正则表达式,以在以下三种情况中的任何一种情况下提取eventId编号25 ,但均未成功:

(?<="eventId":)"(\w+)"(?=,)

Is there any way to achieve this?有什么办法可以做到这一点? ... thanks in advance! ... 提前致谢!

PS: That is a Dataflow java code and just need extract the number without double or single quotes. PS:这是一个数据流 java 代码,只需要提取没有双引号或单引号的数字。

If JSON parser is not available then here is a regex solution.如果 JSON 解析器不可用,那么这里是一个正则表达式解决方案。

Java allows limited dynamism in lookbehind. Java 允许有限的后视动态。 You may use this regex:你可以使用这个正则表达式:

(?<=\"eventId\":[\"']?)\w+

RegEx Demo正则表达式演示

Note addition of an optional " or ' inside the lookbehind condition.请注意在后向条件中添加可选的"'

Code:代码:

Pattern pattern = Pattern.compile("(?<=\"eventId\":[\"']?)\\w+");
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
   System.out.println("Match: " + matcher.group(0));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM