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. }

全部评论

相关推荐

牛至超人:我将凌晨两点给你打电话
点赞 评论 收藏
分享
行云流水1971:这份实习简历的优化建议: 结构清晰化:拆分 “校园经历”“实习经历” 板块(当前内容混杂),按 “实习→校园→技能” 逻辑排版,求职意向明确为具体岗位(如 “市场 / 运营实习生”)。 经历具象化:现有描述偏流程,需补充 “动作 + 数据”,比如校园活动 “负责宣传” 可加 “运营公众号发布 5 篇推文,阅读量超 2000+,带动 300 + 人参与”;实习内容补充 “协助完成 XX 任务,效率提升 X%”。 岗位匹配度:锚定目标岗位能力,比如申请运营岗,突出 “内容编辑、活动执行” 相关动作;申请市场岗,强化 “资源对接、数据统计” 细节。 信息精简:删减冗余表述(如重复的 “负责”),用短句分点,比如 “策划校园招聘会:联系 10 + 企业,组织 200 + 学生参与,到场率达 85%”。 技能落地:将 “Office、PS” 绑定经历,比如 “用 Excel 整理活动数据,输出 3 份分析表;用 PS 设计 2 张活动海报”,避免技能单独罗列。 优化后需强化 “经历 - 能力 - 岗位需求” 的关联,让实习 / 校园经历的价值更直观。 若需要进一步优化服务,私信
实习,投递多份简历没人回...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务