Home > Software design >  Java Rex is not giving the output as expected
Java Rex is not giving the output as expected

Time:08-06

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.

CodePudding user response:

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

P.S. 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

CodePudding user response:

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.

CodePudding user response:

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"
  • Related