2

My string pattern is

"hbfj-nbsp-nbsp-wsefj-f-ejsf-sdfh-sjkf-df-sdjfk-sdfhb-jdgh-nbsp-djg-hdr"

I have tried this pattern "(\\w+)-(\\w+)-(\\w+)-(\\w+)" but it gives exact match. Required is match 0 to 3 times "hbfj-" these type of string.

5
  • 1
    What are you expecting to see? Commented Aug 8, 2013 at 14:17
  • any match upto three hyphen Commented Aug 8, 2013 at 14:20
  • 1
    Could you show expected output/result? Is it only one result or you want to somehow split it? Commented Aug 8, 2013 at 14:22
  • For "a-b-c", should it capture "a-b-" or the whole thing? Commented Aug 8, 2013 at 14:29
  • expected out put "hbfj-nbsp-nbsp-wsefj" , if string is hbfj-nbsp-nbsp then "hbfj-nbsp-nbsp" Commented Aug 8, 2013 at 14:30

2 Answers 2

2

Try use this regex: string.matches("^(\\w+(-|$)){0,3}$")

Sign up to request clarification or add additional context in comments.

1 Comment

expected out put "hbfj-nbsp-nbsp-wsefj" , if string is hbfj-nbsp-nbsp then "hbfj-nbsp-nbsp", it returns boolean expecting substring
1

I think you want to extract the first hyphen separated words (up to 4):

String words = str.replaceAll("^(\\w+(-\\w){0,3})?.*", "$1");

This will return a blank if nothing suitable found.

Comments

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.