简体   繁体   中英

Java Rex is not giving the output as expected

networks[0]/site[9785d8e8-9b1f-3fc0-8271-6e32f58fb725]/equipment/location[144ae20e-be33-32e2-8b52-798e968e88b9]

The objective is to get the 9785d8e8-9b1f-3fc0-8271-6e32f58fb725 from above string. I have written the regex as below. But its giving the output as "location".

.*\\/([^\\/]+)\\[.*\\]$

Could any one suggest me the proper regex to get the 9785d8e8-9b1f-3fc0-8271-6e32f58fb725 from above string.

This should do the trick:

^networks\[\d\]\/site\[([^]]+)\].*$

It will match

  • the literal string networks[]/site[
  • followed by your id
  • followed by ] and arbitrary stuff

You can then extract your ID from the first capturing group.

You can just use site\[(.+?)\] . See the test .

PS You current expression is actually doing the following:

  1. Pass whatever .*
  2. Unless you encounter /
  3. then capture any sequence after / not containing: \ , /
  4. which in turn is followed by [] with whatever content straight away and residing at the very end of the string.

So the only matching part is location

You can search using this regex:

^[^/]+/[^\[/]*\[|\].*

and replace with empty string.

RegEx Demo

RegEx Explanation:

  • ^[^/]+/[^\[/]*\[ : This pattern matches text before first / then / followed by text till it gets next [
  • \].* : Matches ] and everything afterwards

Code:

String s = "networks[0]/site[9785d8e8-9b1f-3fc0-8271-6e32f58fb725]/equipment/location[144ae20e-be33-32e2-8b52-798e968e88b9]";

String r = s.replaceAll("^[^/]+/[^\\[/]*\\[|\\].*", "");
//=> "9785d8e8-9b1f-3fc0-8271-6e32f58fb725"

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