Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex : Using Regex in Java 8

Tags:

java

string

regex

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 ?

like image 203
CHARAFI Saad Avatar asked Sep 04 '26 13:09

CHARAFI Saad


1 Answers

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]
like image 101
YCF_L Avatar answered Sep 06 '26 02:09

YCF_L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!