Ashish Chaurasia
Ashish Chaurasia

Reputation: 1737

java regex for finding the matching string

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.

Upvotes: 2

Views: 88

Answers (2)

Bohemian
Bohemian

Reputation: 424973

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.

Upvotes: 1

Сашка724ая
Сашка724ая

Reputation: 682

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

Upvotes: 2

Related Questions