简体   繁体   中英

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.

我会做替换和拆分。

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

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

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM