Deepak Singh
Deepak Singh

Reputation: 460

How to split after some specific word

I have to split word when find ^ and _live in String. I am able to split only match ^ but I have to split when match ^ and _live. The result should be

[ab,cb,db,qw]

How will be done?

String usergroup="ab_live^cb_live^db_live^qw_live";
String[] userGroupParts = usergroup.split("\\^");                
List<String> listUserGroupParts = Arrays.asList(userGroupParts);
Set<String> SMGroupDetails = new HashSet<String>(listUserGroupParts);

Upvotes: 0

Views: 79

Answers (3)

Abra
Abra

Reputation: 20923

I would not use method split, of class java.lang.String, but rather regular expressions.

You want to create a list of all the occurrences of the letters that appear after the literal character ^ and before the string _live. The following code achieves this. (Explanations after the code.)

/* Required imports:
 * java.util.ArrayList
 * java.util.List
 * java.util.regex.Matcher
 * java.util.regex.Pattern
 */
String usergroup="ab_live^cb_live^db_live^qw_live";
Pattern pattern = Pattern.compile("\\^?(\\w+)_live");
Matcher matcher = pattern.matcher(usergroup);
List<String> listUserGroupParts = new ArrayList<>();
while (matcher.find()) {
    listUserGroupParts.add(matcher.group(1));
}
System.out.println(listUserGroupParts);

The regular expression, i.e. the argument to method compile in the above code, looks for the following:

  1. the literal character ^, followed by
  2. at least one word character, followed by
  3. the literal string _live

Note that part 2 is surrounded by brackets which means it is referred to as a group.

The while loop searches usergroup for the next occurrence of the regular expression and each time it finds an occurrence, it extracts the contents of the group and adds it to the List.

The output when running the above code is:

[ab, cb, db, qw]

Upvotes: 0

mkemper
mkemper

Reputation: 79

This should do it...

public static void main(String[] args) {
    String usergroup = "ab_live^cb_live^db_live^qw_live";
    String[] userGroupParts = usergroup.split("\\^");
    for (int i=0; i<userGroupParts.length; i++) userGroupParts[i] = userGroupParts[i].split("\\_")[0];
    for (String s : userGroupParts) System.out.println(s);
}

i.e. you first split by ^ and then you cycle through the resulting strings splitting on _, retaining only the bit prior to the underscore

Upvotes: 1

Sergey Afinogenov
Sergey Afinogenov

Reputation: 2222

We can say that split separator should be _live^ or just _live at the end of the line.

That's why regular expression must consist of _live and capturing group (\^|$) witch includes two alternatives separated by | (or):

1st alternative \^ matches the character ^ literally (by using escape character before) and 2nd alternative $ asserts position at the end of a line.

String[] userGroupParts = usergroup.split("_live(\\^|$)");

Upvotes: 1

Related Questions