Detailed explanation of java string separation (my first blog)

The split function of java is one of the common functions that is easy to forget the rules. My first blog explains this problem in detail, deepening understanding, for your reference

  1. function definition

       public String[] split(String regex,int limit)

       Splits this string based on matching the given regular expression. 

     2.  Function Rules
       The array returned by this method contains substrings of this string, each substring terminated by another substring matching the given expression, or terminated at the end of this string, skipping this when continuing Matches a substring of the given expression. The substrings in the array are in the order in which they appear in this string. If the expression does not match any part of the input, the resulting array has only one element, this string. 
       The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than 0, the pattern will be applied at most n - 1 times, the length of the array will be no greater than n, and the last item of the array will contain all input beyond the last matched delimiter. If n is non-positive, the pattern will be applied as many times as possible, and the array can be of any length. If n is 0, the pattern will be applied as many times as possible, the array can be of any length, and trailing empty strings will be discarded. 
       For example, the string "boo:and:foo" with these parameters produces the following result: 
       Regex Limit Result 
           : 2 { "boo", "and:foo" } 
           : 5 { "boo", "and", "foo" } 
           : -2 { "boo", "and", "foo" } 
          o 5 { "b", "", 
          o        -2       { "b", "", ":and:f", "", "" } 
          o        0        { "b", "", ":and:f" } 

Help understanding: "boo:and:foo"=""+b+""+"o"+""+"o"........, that is, the empty string is also included in the parsing.

       In addition, split with no restriction parameter is equivalent to restricting the parameter to 0.
       public String[] split(String regex) Splits this string according to the matching of the given regular expression. 
This method acts as if the two-argument split method was called with the given expression and a limit argument of 0. Therefore, the trailing empty string is not included in the resulting array. 
For example, the string "boo:and:foo" uses these expressions to produce the following result: 
      Regex result 
      : { "boo", "and", "foo" } 

      o      { "b", "", ":and:f" } 

  Finally, you only need to remember that empty strings also participate in the splitting rules, and that the limit is 0, which will remove the empty strings at the end, so there will be no confusion.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324777366&siteId=291194637