3

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 ?

4
  • 3
    Why not just use substring? Commented Dec 23, 2019 at 19:38
  • 1
    Because my String is variable There always a number after -- Commented Dec 23, 2019 at 19:41
  • You're using '-' as a field delimiter, and implicitly not allowing any of the fields themselves to start or end with '-'. That is, dfwx--05 is always a single field and cannot represent two fields dfwx and -05. I hope this is just a practice/learning and not in use with real data. :-) Commented Dec 23, 2019 at 20:13
  • Just note, that the title should be significant, not a standard one Commented Dec 23, 2019 at 21:06

2 Answers 2

7

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]
Sign up to request clarification or add additional context in comments.

1 Comment

String str = "dfwx--05-dfpixc3"; Arrays.stream(str.split("\\b-\\b")).forEach(System.out::println); does the perfect job.
5

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:

https://repl.it/repls/ImpressionableBronzeMice

1 Comment

I would just do it like this. repl.it/repls/ImpressionableBronzeMice - Good point about additional dashes. I actually like your answer better personally than YCF_L's. Since it deals with the - character on it own. That in my eyes is cleaner/clearer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.