Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. You can use Lookahead and Lookbehind. Like this:
  2.  
  3. System.out.println(Arrays.toString("a;b;c;d".split("(?<=;)")));
  4. System.out.println(Arrays.toString("a;b;c;d".split("(?=;)")));
  5. System.out.println(Arrays.toString("a;b;c;d".split("((?<=;)|(?=;))")));
  6. And you will get:
  7.  
  8. [a;, b;, c;, d]
  9. [a, ;b, ;c, ;d]
  10. [a, ;, b, ;, c, ;, d]
  11.  
  12. The last one is what you want.
  13.  
  14. ((?<=;)|(?=;)) equals to select an empty character before ; or after ;.
  15.  
  16. Hope this helps.
  17.  
  18. EDIT Fabian Steeg comments on Readability is valid. Readability is always the problem for RegEx. One thing, I do to help easing this is to create a variable whose name represent what the regex does and use Java String format to help that. Like this:
  19.  
  20. static public final String WITH_DELIMITER = "((?<=%1$s)|(?=%1$s))";
  21. ...
  22. public void someMethod() {
  23. ...
  24. final String[] aEach = "a;b;c;d".split(String.format(WITH_DELIMITER, ";"));
  25. ...
  26. }
  27. ...
  28. This helps a little bit. :-D
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement