0

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.

5 Answers 5

1

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(" ");
Sign up to request clarification or add additional context in comments.

2 Comments

how about if is is case sensitive
@AlexMan updated my answer. You have to add insensitive flag with (?i).
1

I would do replacing and splitting.

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

Comments

1

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(" ");

1 Comment

do substring have int and string parameters
1

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

Comments

0

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)

1 Comment

how to write that , str.split("\\is([^\?]+)") is giving exception

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.