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 :
\\b
represents 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]
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 dash If 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:
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.