Reputation: 1160
I have one string which i need to divide into two parts using regex
String string = "2pbhk";
This string i need to divide into 2p
and bhk
More over second part should always be bhk
or rk
, as strings can be one of 1bhk
, 5pbhk
etc
I have tried
String pattern = ([^-])([\\D]*);
Upvotes: 1
Views: 944
Reputation: 627086
In case you are looking to split strings that end with rk
or bhk
but not necessarily at the end of the string (i.e. at the word boundaries), you need to use a regex with \\b
:
String[] arr = "5ddddddpbhk".split("(?=(?:rk|bhk)\\b)");
System.out.println(Arrays.toString(arr));
If you want to allow splitting inside a longer string, remove the \\b
.
If you only split individual words, use $
instead of \\b
(i.e. end of string):
(?=(?:rk|bhk)$)
Here is my IDEONE demo
Upvotes: 0
Reputation: 8332
This should do the trick:
(.*)(bhk|rk)
First capture holds the "number" part, and the second bhk OR rk.
Regards
Upvotes: 1
Reputation: 14438
You can use the following regex "(?=bhk|rk)"
with split.
str.split("(?=bhk|rk)");
This will split it if there is one of bhk
or rk
.
Upvotes: 2
Reputation: 2820
String string = "2pbhk";
String first_part, second_part = null;
if(string.contains("bhk")){
first_part = string.substring(0, string.indexOf("bhk"));
second_part = "bhk";
}
else if(string.contains("rk")){
first_part = string.substring(0, string.indexOf("rk"));
second_part = "rk";
}
Try the above once, not using regex but should work.
Upvotes: 0