Examples of several ways to get substrings in Java

  • 2020-06-01 09:37:02
  • OfStack

First, if you have a string like this:

String s = "共 100 页, 1 2 3 4...";

What if I want to take out the 100?

Method 1: adopt the split approach


System.out.println(s.split(" ")[1]); or System.out.println(s.split("\\s")[1]);

If "empty" has more than one, it can be like this:


System.out.println(s.split("\\s+")[1]);

Note :split is regular, \s means space in the regular, + means at least 1 space in the regular, that is, 1 or more, so \s+ means at least 1 space

Method 2: use the indexOf approach


int begin = s.indexOf(" ");
int end = s.indexOf(" ", begin+1);
System.out.println(s.substring(begin+1, end));

Method 3: regex

Encapsulated 1 regular class:


public class RegExp {
 
  public boolean match(String reg, String str) {
    return Pattern.matches(reg, str);
  }
 
  public List<String> find(String reg, String str) {
    Matcher matcher = Pattern.compile(reg).matcher(str);
    List<String> list = new ArrayList<String>();
    while (matcher.find()) {
      list.add(matcher.group());
    }
    return list;
  }
   
  public String find(String reg, String str, int index) {
    Matcher matcher = Pattern.compile(reg).matcher(str);
    if (matcher.find()) {
      return matcher.group(index);
    }
    return null;
  }
 
  public String findString(String reg, String str) {
    String returnStr = null;
    List<String> list = this.find(reg, str);
    if (list.size() != 0)
      returnStr = list.get(0);
    return returnStr;
  }
 
}

 RegExp re = new RegExp();
 System.out.println(re.findString("\\d+", s));

 System.out.println(re.findString("(?<= A total of ).*?\\d+", s).trim());

Note: \d in regular means number, (? < = total) is a pre-check mode

Method 4: use the replaceFirst approach


System.out.println(s.replaceFirst(".*?(\\d+).*", "$1"));

replaceFirst also supports regularization

Note: the & # 63; In the regex, represents the minimum matching pattern, and $1 represents the contents of the first () representation.

conclusion

Three of the four methods above have something to do with regularity, so the ability to have a definite regular representation is essential if you want to play with strings!

PS: here are two more handy regular expression tools for you to use:

JavaScript regular expression online testing tool:
http://tools.ofstack.com/regex/javascript

Online regular expression generation tool:
http://tools.ofstack.com/regex/create_reg

The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: