+ 1

Nested Dashes

Hi, Is there a possibility in java to remove nested dashes and leave unnestested dashes untouched? Example: Hello-World - Emmanuel I want the dash between Hello and World removed and the dash between World and Emmanuel not removed. I can use a split method but it removes all dashes.

16th Jan 2019, 6:11 AM
Sibusiso Mbambo
4 ответов
+ 4
Try this var s = "Hello-world - Emmanuel"; s = s.replaceAll("-(?=\\w)",""); //HelloWorld - Emmanuel This is a code that consists of lookaheads and look behinds as Tibor Santa said
16th Jan 2019, 1:12 PM
Seniru
Seniru - avatar
+ 3
You can either use regular expressions or do it manually: Replace nested dashes (the ones you want to keep) with some unique expression like _&*_ (expression may contain anything but dashes). Replace all dashes with ' ' (i.e. remove them). Replace the expression from above with nested dashes.
16th Jan 2019, 7:26 AM
Anna
Anna - avatar
+ 2
An easy way would be to loop though the letters of the string, and check for each dash if the previous and following char is whitespace. That does not manipulate the original string. If you are not scared of regular expressions then I think "negative lookbehind" and "negative lookahead" is what you need to check, here is an article: https://regular-expressions.mobi/lookaround.html?wlr=1
16th Jan 2019, 7:36 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Thank you guys for your input!
16th Jan 2019, 7:39 AM
Sibusiso Mbambo