简体   繁体   English

使用Pattern Java中的正则表达式

[英]Regular Expressions in Using Pattern java

I have a string as below. 我有一个字符串如下。

$Alarm:com.Alarm(a  ==  123 || (count  ==  12345 , time  matches  "24"))

whenever i encounter the above string i need to generate the following string.I mean i need to append the string "from Stream" as below. 每当遇到上面的字符串时,我都需要生成以下字符串。我的意思是我需要在字符串后面附加“来自Stream”。

$Alarm:com.Alarm(a  ==  123 || (count  ==  12345 , time  matches  "24")) from Stream.

I am currently using the following pattern to acheive the same in java. 我目前正在使用以下模式在Java中实现相同的功能。

Pattern eventPattern = Pattern.compile(".*?\\.Alarm\\(.*?\\)");

But i am getting the following output. 但是我得到以下输出。

$Alarm:com.Alarm(a  ==  123 || (count  ==  12345 , time  matches  "24") from Stream )

Please provide me some pointers to acheive the correct output.The regular expression should consider only the last paranthesis. 请向我提供一些指针以实现正确的输出。正则表达式应仅考虑最后一个括号。

You need to include parens matching in your Pattern. 您需要在模式中包含匹配的括号。 Something like the following: 类似于以下内容:

Pattern eventPattern = Pattern.compile(".*?\\.Alarm\\(([^\\(]*?|\\([^\\)]*?\\))*\\)");

Things up to and including the first open parens: .*?\\\\.Alarm\\\\( 直到并包括第一个打开的括号的内容: .*?\\\\.Alarm\\\\(

Stuff outside any internal parens: [^\\\\(]*? 在内部任何内部括号之外的内容: [^\\\\(]*?

Internal parens pair: \\\\([^\\\\)]*?\\\\) 内部对对: \\\\([^\\\\)]*?\\\\)

Match any number of stuff outside parens or within a parens pair: ([^\\\\(]*?|\\\\([^\\\\)]*?\\\\))* 匹配在parens外部或parens对内的任意数量的东西: ([^\\\\(]*?|\\\\([^\\\\)]*?\\\\))*

This RegexPlanet site is a great place to play with regexes to see what will work. 这个RegexPlanet网站是一个与正则表达式一起玩的好地方,以查看将如何工作。

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

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