String.split()分割字符串,转义字符

1、String.split()

String有个方法是分割字符串  .split()。但是有写字符串是需要转义才能分割,不然就会出错。

需要转义的字符串:.  $  |   (   )  [   {   ^  ?  *  +  \\      共12个特殊字符,遇到以这些字符进行分割字符串的时候,需要在这些特殊字符前加双反斜杠 \\

例如:

str.split("\\.")

str.split("\\$")

str.split("\\|")  

str.split("\\(")  

str.split("\\)") 

str.split("\\[")

str.split("\\{")

str.split("\\^")  

str.split("\\?")  

str.split("\\*") 

str.split("\\+")

str.split("\\\\")

2、源码:


 
 
  1. public String[] split(String regex) {
  2.         return split(regex, 0);
  3.     }
  4. public String[] split(String regex, int limit) {
  5. /* fastpath if the regex is a
  6. (1)one-char String and this character is not one of the
  7. RegEx's meta characters ".$|()[{^?*+\\", or
  8. (2)two-char String and the first char is the backslash and
  9. the second is not the ascii digit or ascii letter.
  10. */
  11. char ch = 0;
  12. if (((regex.value.length == 1 &&
  13. ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
  14. (regex.length() == 2 &&
  15. regex.charAt( 0) == '\\' &&
  16. (((ch = regex.charAt( 1))- '0')|( '9'-ch)) < 0 &&
  17. ((ch- 'a')|( 'z'-ch)) < 0 &&
  18. ((ch- 'A')|( 'Z'-ch)) < 0)) &&
  19. (ch < Character.MIN_HIGH_SURROGATE ||
  20. ch > Character.MAX_LOW_SURROGATE))
  21. {
  22. int off = 0;
  23. int next = 0;
  24. boolean limited = limit > 0;
  25. ArrayList<String> list = new ArrayList<>();
  26. while ((next = indexOf(ch, off)) != - 1) {
  27. if (!limited || list.size() < limit - 1) {
  28. list.add(substring(off, next));
  29. off = next + 1;
  30. } else { // last one
  31. //assert (list.size() == limit - 1);
  32. list.add(substring(off, value.length));
  33. off = value.length;
  34. break;
  35. }
  36. }
  37. // If no match was found, return this
  38. if (off == 0)
  39. return new String[]{ this};
  40. // Add remaining segment
  41. if (!limited || list.size() < limit)
  42. list.add(substring(off, value.length));
  43. // Construct result
  44. int resultSize = list.size();
  45. if (limit == 0)
  46. while (resultSize > 0 && list.get(resultSize - 1).length() == 0)
  47. resultSize--;
  48. String[] result = new String[resultSize];
  49. return list.subList( 0, resultSize).toArray(result);
  50. }
  51. return Pattern.compile(regex).split( this, limit);
  52. }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值