Please tell me how to create a regexp for such a line /utils/add/message ? such /действие can be any number.

This comes to the controller and I need to figure out what actions to do, where to redirect.

Thank.

  • Do you really need regexp? If so, what is expected of him, what should be the output? Or maybe a banal explode() enough? - PinkTux
  • @PinkTux I tried to do .split("/") but this is a little different for empty values ​​appear. it will be convenient to find the matcher all the matches (groups) and extract them. - Tsyklop
  • one
    And what's the problem after .split("/") in the array to drop empty values, and work with the rest? - I. Perevoz
  • @ I.Perevoz after .split() we get an array of strings - String[] . This is not a List - there you can not delete the extra. Only by writing to another array of strings. I thought how to make it easier and more flexible. - Tsyklop
  • And myValue.replaceFirst("^/+", "").split("/+") will not work? In any case, it will not be possible to use the regular schedule with groups, since The number of these groups is unknown in advance. - Wiktor Stribiżew

1 answer 1

If you really do not want to do through. .split("/")

 public static void main(String[] args) { String checkString = "/aaa/bbb/ccc//abc/bcd/erf/ /"; List<String> commands = new ArrayList<>(); if (checkString.startsWith("/") && checkString.endsWith("/")){ String pattern = "/[A-Za-z]+"; Matcher m = Pattern.compile(pattern).matcher(checkString); while (m.find()){ String cmd = m.group(); commands.add(cmd.substring(1,cmd.length())); } } commands.forEach(System.out::println); } 

However, so much easier:

 public static void main(String[] args) { String checkString = "/aaa/bbb/ccc//abc/bcd/erf/ /"; if (checkString.startsWith("/") && checkString.endsWith("/")) { List<String> commands = new ArrayList<>(); String[] cmds = checkString.split("/"); for (String s : cmds) if (s.length() != 0) commands.add(s); commands.forEach(System.out::println); } }