I want to manipulate a String, my String are :
String string = "dfwx--05-dfpixc3"
I want my output to be like :
dfwx--05
dfpixc3
So the separator is - and not --
moreover, can I solve this problem using Matcher class Pattern class ?
You can use split with this regex \b-\b with Word Boundaries like so :
\brepresents an anchor like caret (it is similar to$and^) matching positions where one side is a word character (like\w) and the other side is not a word character (for instance it may be the beginning of the string or a space character).
String[] split = string.split("\\b-\\b");
Because my String is variable There always a number after --
Another solution could be by using positive lookbehind, like so (?<=\d)- :
String[] split = string.split("(?<=\\d)-");
Outputs
[dfwx--05, dfpixc3]
String str = "dfwx--05-dfpixc3"; Arrays.stream(str.split("\\b-\\b")).forEach(System.out::println); does the perfect job.You can make use of lookarounds:
(?<!-)-(?!-)
(?<!-) - make sure the preceding char is not a dash- - make sure we are looking at a dash(?!-) - make sure the following char is not a dashIf I'm not mistaken, the code would be:
string.split("(?<!-)-(?!-)");
I don't know which online tester is best for Java but see https://regex101.com/r/LVXDdH/1 for a PCRE example.
Thank you JGFMK for this Java specific test site:
-' as a field delimiter, and implicitly not allowing any of the fields themselves to start or end with '-'. That is,dfwx--05is always a single field and cannot represent two fieldsdfwxand-05. I hope this is just a practice/learning and not in use with real data. :-)