简体   繁体   中英

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.

$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.

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\\\\(

Stuff outside any internal parens: [^\\\\(]*?

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

Match any number of stuff outside parens or within a parens pair: ([^\\\\(]*?|\\\\([^\\\\)]*?\\\\))*

This RegexPlanet site is a great place to play with regexes to see what will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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