-4

I have a string in format like "one / two / three" and I need only the first one (before the first foreslash). I tried it like that:

if (text.contains("/")) {
        int i = text.indexOf("/");
        return text.subSequence(0, i).toString();
    }

This solution works but I think it would be better to write simple text.replace() function. Tried this regex "\\/(.*)" but it didn`t work.

5
  • Did you try splitting on a /? Dec 28, 2018 at 10:13
  • Like this?text.split("/")[0];
    – cuteBrick
    Dec 28, 2018 at 10:16
  • Why would you want to replace? and why would you use subSequence instead of substring without making use of toString()?
    – SMA
    Dec 28, 2018 at 10:19
  • Yes, split on a / and then join the second and the third part again ideone.com/NHlFZn Dec 28, 2018 at 10:27
  • 1
    Using index and substring is fine (but cumbersome). But split ? That's just a lazy hack here. Dec 28, 2018 at 10:29

4 Answers 4

0

replace doesn't take a regex as parameter but just tries to replace the passed char sequence.

You may use replaceFirst:

 return text.replaceFirst("/.*", "");

(note that there's nothing to escape and no group is necessary)

0
0

In Kotlin you want something like string.replace("/.*".toRegex(), "")

0
-1

You can try the below code it will replace after first slash,

 text.replaceAll("\\/[^\\/].*", "")
-1

replace will not work in this case use this .

return text.replaceAll("/.", "");

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.