Alex Man
Alex Man

Reputation: 4886

split string using regular expression in java

I am having a string "What is your name?" in a variable like as shown below.

String str="What is your name ?";
String[] splitString =str.split("\\is+");

I want to split the string in such a way that I want only those words between is and ?. ie. your and name by using regular expression

can anyone tell me some solution for this.

Upvotes: 0

Views: 136

Answers (5)

SoWhat
SoWhat

Reputation: 5622

Use the regex is([^\?]+) and capture the first subgroup and split it This is a slightly longer approach, but is the right way to do this in core Java. You can use a regex library to do this

   import java.util.regex.Matcher;
   import java.util.regex.Pattern;
    //Later
    String pattern="`is([^\?]+)"
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(str);
    var words=m.group(1)

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 30995

You could use something like this:

String str="What is your name ?";
String[] splitString = str.replaceAll(".*? is (.*) \\?", "$1").split(" ");
// [your, name]

IdeOne demo

Update: if you want to match case insensitive, just add the insensitive flag:

String str="What is your name ?";
String[] splitString = str.replaceAll("(?i).*? is (.*) \\?", "$1").split(" ");

Upvotes: 1

Stanislav
Stanislav

Reputation: 28106

You can use replaceFirst and then split

String str="What is your name?";
String[] splitString =str.replaceFirst(".*[[Ii][Ss]]\\s+","").split("\\s*\\?.*|\\s+");
for (int i=0; i< splitString.length; i++){
    System.out.println("-"+splitString[i]);
}

replaceFirst is needed to delete the first part of string, which is What is. The regex .*[[Ii][Ss]]\\s+ means - any signs before case insensitive IS and all the spaces after that. If it'll stay, we will get an additional empty string while splitting.

After replacing, it splits the rest string by

\\s+ one or more whitespaces

and

\\s*\\?.* the ? sign with all whitespaces before and any characters after

Upvotes: 1

hotzst
hotzst

Reputation: 7496

The poor mans solution would be to extract the substing first and use the split on top of that:

String substring = str.substring(str.indexOf("is")+2,str.indexOf("?"));
String[] splitString =substring.trim().split(" ");

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

I would do replacing and splitting.

 string.replaceFirst(".*\\bis\\b\\s*(.*?)\\s*\\?.*", "$1").split("\\s+");

Upvotes: 1

Related Questions