StringUtils.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. package com.ruoyi.common.utils;
  2. import com.ruoyi.common.constant.Constants;
  3. import com.ruoyi.common.core.text.StrFormatter;
  4. import org.springframework.util.AntPathMatcher;
  5. import org.springframework.web.multipart.MultipartFile;
  6. import java.io.IOException;
  7. import java.util.*;
  8. import java.util.regex.Matcher;
  9. import java.util.regex.Pattern;
  10. /**
  11. * 字符串工具类
  12. */
  13. public class StringUtils extends org.apache.commons.lang3.StringUtils {
  14. /**
  15. * 空字符串
  16. */
  17. private static final String NULLSTR = "";
  18. /**
  19. * 下划线
  20. */
  21. private static final char SEPARATOR = '_';
  22. /**
  23. * 获取参数不为空值
  24. *
  25. * @param value defaultValue 要判断的value
  26. * @return value 返回值
  27. */
  28. public static <T> T nvl(T value, T defaultValue) {
  29. return value != null ? value : defaultValue;
  30. }
  31. /**
  32. * * 判断一个Collection是否为空, 包含List,Set,Queue
  33. *
  34. * @param coll 要判断的Collection
  35. * @return true:为空 false:非空
  36. */
  37. public static boolean isEmpty(Collection<?> coll) {
  38. return isNull(coll) || coll.isEmpty();
  39. }
  40. /**
  41. * * 判断一个Collection是否非空,包含List,Set,Queue
  42. *
  43. * @param coll 要判断的Collection
  44. * @return true:非空 false:空
  45. */
  46. public static boolean isNotEmpty(Collection<?> coll) {
  47. return !isEmpty(coll);
  48. }
  49. /**
  50. * * 判断一个对象数组是否为空
  51. *
  52. * @param objects 要判断的对象数组
  53. * * @return true:为空 false:非空
  54. */
  55. public static boolean isEmpty(Object[] objects) {
  56. return isNull(objects) || (objects.length == 0);
  57. }
  58. /**
  59. * * 判断一个对象数组是否非空
  60. *
  61. * @param objects 要判断的对象数组
  62. * @return true:非空 false:空
  63. */
  64. public static boolean isNotEmpty(Object[] objects) {
  65. return !isEmpty(objects);
  66. }
  67. /**
  68. * * 判断一个Map是否为空
  69. *
  70. * @param map 要判断的Map
  71. * @return true:为空 false:非空
  72. */
  73. public static boolean isEmpty(Map<?, ?> map) {
  74. return isNull(map) || map.isEmpty();
  75. }
  76. /**
  77. * * 判断一个Map是否为空
  78. *
  79. * @param map 要判断的Map
  80. * @return true:非空 false:空
  81. */
  82. public static boolean isNotEmpty(Map<?, ?> map) {
  83. return !isEmpty(map);
  84. }
  85. /**
  86. * * 判断一个字符串是否为空串
  87. *
  88. * @param str String
  89. * @return true:为空 false:非空
  90. */
  91. public static boolean isEmpty(String str) {
  92. return isNull(str) || NULLSTR.equals(str.trim());
  93. }
  94. /**
  95. * * 判断一个字符串是否为非空串
  96. *
  97. * @param str String
  98. * @return true:非空串 false:空串
  99. */
  100. public static boolean isNotEmpty(String str) {
  101. return !isEmpty(str);
  102. }
  103. /**
  104. * * 判断一个对象是否为空
  105. *
  106. * @param object Object
  107. * @return true:为空 false:非空
  108. */
  109. public static boolean isNull(Object object) {
  110. return object == null;
  111. }
  112. /**
  113. * * 判断一个对象是否非空
  114. *
  115. * @param object Object
  116. * @return true:非空 false:空
  117. */
  118. public static boolean isNotNull(Object object) {
  119. return !isNull(object);
  120. }
  121. /**
  122. * * 判断一个对象是否是数组类型(Java基本型别的数组)
  123. *
  124. * @param object 对象
  125. * @return true:是数组 false:不是数组
  126. */
  127. public static boolean isArray(Object object) {
  128. return isNotNull(object) && object.getClass().isArray();
  129. }
  130. /**
  131. * 去空格
  132. */
  133. public static String trim(String str) {
  134. return (str == null ? "" : str.trim());
  135. }
  136. /**
  137. * 截取字符串
  138. *
  139. * @param str 字符串
  140. * @param start 开始
  141. * @return 结果
  142. */
  143. public static String substring(final String str, int start) {
  144. if (str == null) {
  145. return NULLSTR;
  146. }
  147. if (start < 0) {
  148. start = str.length() + start;
  149. }
  150. if (start < 0) {
  151. start = 0;
  152. }
  153. if (start > str.length()) {
  154. return NULLSTR;
  155. }
  156. return str.substring(start);
  157. }
  158. /**
  159. * 截取字符串
  160. *
  161. * @param str 字符串
  162. * @param start 开始
  163. * @param end 结束
  164. * @return 结果
  165. */
  166. public static String substring(final String str, int start, int end) {
  167. if (str == null) {
  168. return NULLSTR;
  169. }
  170. if (end < 0) {
  171. end = str.length() + end;
  172. }
  173. if (start < 0) {
  174. start = str.length() + start;
  175. }
  176. if (end > str.length()) {
  177. end = str.length();
  178. }
  179. if (start > end) {
  180. return NULLSTR;
  181. }
  182. if (start < 0) {
  183. start = 0;
  184. }
  185. if (end < 0) {
  186. end = 0;
  187. }
  188. return str.substring(start, end);
  189. }
  190. /**
  191. * 格式化文本, {} 表示占位符<br>
  192. * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
  193. * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
  194. * 例:<br>
  195. * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
  196. * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
  197. * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
  198. *
  199. * @param template 文本模板,被替换的部分用 {} 表示
  200. * @param params 参数值
  201. * @return 格式化后的文本
  202. */
  203. public static String format(String template, Object... params) {
  204. if (isEmpty(params) || isEmpty(template)) {
  205. return template;
  206. }
  207. return StrFormatter.format(template, params);
  208. }
  209. /**
  210. * 是否为http(s)://开头
  211. *
  212. * @param link 链接
  213. * @return 结果
  214. */
  215. public static boolean ishttp(String link) {
  216. return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS);
  217. }
  218. /**
  219. * 字符串转set
  220. *
  221. * @param str 字符串
  222. * @param sep 分隔符
  223. * @return set集合
  224. */
  225. public static final Set<String> str2Set(String str, String sep) {
  226. return new HashSet<String>(str2List(str, sep, true, false));
  227. }
  228. /**
  229. * 字符串转list
  230. *
  231. * @param str 字符串
  232. * @param sep 分隔符
  233. * @param filterBlank 过滤纯空白
  234. * @param trim 去掉首尾空白
  235. * @return list集合
  236. */
  237. public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
  238. List<String> list = new ArrayList<String>();
  239. if (StringUtils.isEmpty(str)) {
  240. return list;
  241. }
  242. // 过滤空白字符串
  243. if (filterBlank && StringUtils.isBlank(str)) {
  244. return list;
  245. }
  246. String[] split = str.split(sep);
  247. for (String string : split) {
  248. if (filterBlank && StringUtils.isBlank(string)) {
  249. continue;
  250. }
  251. if (trim) {
  252. string = string.trim();
  253. }
  254. list.add(string);
  255. }
  256. return list;
  257. }
  258. /**
  259. * 判断给定的set列表中是否包含数组array 判断给定的数组array中是否包含给定的元素value
  260. *
  261. * @param collection 给定的集合
  262. * @param array 给定的数组
  263. * @return boolean 结果
  264. */
  265. public static boolean containsAny(Collection<String> collection, String... array) {
  266. if (isEmpty(collection) || isEmpty(array)) {
  267. return false;
  268. } else {
  269. for (String str : array) {
  270. if (collection.contains(str)) {
  271. return true;
  272. }
  273. }
  274. return false;
  275. }
  276. }
  277. /**
  278. * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写
  279. *
  280. * @param cs 指定字符串
  281. * @param searchCharSequences 需要检查的字符串数组
  282. * @return 是否包含任意一个字符串
  283. */
  284. public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {
  285. if (isEmpty(cs) || isEmpty(searchCharSequences)) {
  286. return false;
  287. }
  288. for (CharSequence testStr : searchCharSequences) {
  289. if (containsIgnoreCase(cs, testStr)) {
  290. return true;
  291. }
  292. }
  293. return false;
  294. }
  295. /**
  296. * 驼峰转下划线命名
  297. */
  298. public static String toUnderScoreCase(String str) {
  299. if (str == null) {
  300. return null;
  301. }
  302. StringBuilder sb = new StringBuilder();
  303. // 前置字符是否大写
  304. boolean preCharIsUpperCase = true;
  305. // 当前字符是否大写
  306. boolean curreCharIsUpperCase = true;
  307. // 下一字符是否大写
  308. boolean nexteCharIsUpperCase = true;
  309. for (int i = 0; i < str.length(); i++) {
  310. char c = str.charAt(i);
  311. if (i > 0) {
  312. preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
  313. } else {
  314. preCharIsUpperCase = false;
  315. }
  316. curreCharIsUpperCase = Character.isUpperCase(c);
  317. if (i < (str.length() - 1)) {
  318. nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
  319. }
  320. if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
  321. sb.append(SEPARATOR);
  322. } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
  323. sb.append(SEPARATOR);
  324. }
  325. sb.append(Character.toLowerCase(c));
  326. }
  327. return sb.toString();
  328. }
  329. /**
  330. * 是否包含字符串
  331. *
  332. * @param str 验证字符串
  333. * @param strs 字符串组
  334. * @return 包含返回true
  335. */
  336. public static boolean inStringIgnoreCase(String str, String... strs) {
  337. if (str != null && strs != null) {
  338. for (String s : strs) {
  339. if (str.equalsIgnoreCase(trim(s))) {
  340. return true;
  341. }
  342. }
  343. }
  344. return false;
  345. }
  346. /**
  347. * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld
  348. *
  349. * @param name 转换前的下划线大写方式命名的字符串
  350. * @return 转换后的驼峰式命名的字符串
  351. */
  352. public static String convertToCamelCase(String name) {
  353. StringBuilder result = new StringBuilder();
  354. // 快速检查
  355. if (name == null || name.isEmpty()) {
  356. // 没必要转换
  357. return "";
  358. } else if (!name.contains("_")) {
  359. // 不含下划线,仅将首字母大写
  360. return name.substring(0, 1).toUpperCase() + name.substring(1);
  361. }
  362. // 用下划线将原始字符串分割
  363. String[] camels = name.split("_");
  364. for (String camel : camels) {
  365. // 跳过原始字符串中开头、结尾的下换线或双重下划线
  366. if (camel.isEmpty()) {
  367. continue;
  368. }
  369. // 首字母大写
  370. result.append(camel.substring(0, 1).toUpperCase());
  371. result.append(camel.substring(1).toLowerCase());
  372. }
  373. return result.toString();
  374. }
  375. /**
  376. * 驼峰式命名法 例如:user_name->userName
  377. */
  378. public static String toCamelCase(String s) {
  379. if (s == null) {
  380. return null;
  381. }
  382. s = s.toLowerCase();
  383. StringBuilder sb = new StringBuilder(s.length());
  384. boolean upperCase = false;
  385. for (int i = 0; i < s.length(); i++) {
  386. char c = s.charAt(i);
  387. if (c == SEPARATOR) {
  388. upperCase = true;
  389. } else if (upperCase) {
  390. sb.append(Character.toUpperCase(c));
  391. upperCase = false;
  392. } else {
  393. sb.append(c);
  394. }
  395. }
  396. return sb.toString();
  397. }
  398. /**
  399. * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
  400. *
  401. * @param str 指定字符串
  402. * @param strs 需要检查的字符串数组
  403. * @return 是否匹配
  404. */
  405. public static boolean matches(String str, List<String> strs) {
  406. if (isEmpty(str) || isEmpty(strs)) {
  407. return false;
  408. }
  409. for (String pattern : strs) {
  410. if (isMatch(pattern, str)) {
  411. return true;
  412. }
  413. }
  414. return false;
  415. }
  416. /**
  417. * 判断url是否与规则配置:
  418. * ? 表示单个字符;
  419. * * 表示一层路径内的任意字符串,不可跨层级;
  420. * ** 表示任意层路径;
  421. *
  422. * @param pattern 匹配规则
  423. * @param url 需要匹配的url
  424. * @return
  425. */
  426. public static boolean isMatch(String pattern, String url) {
  427. AntPathMatcher matcher = new AntPathMatcher();
  428. return matcher.match(pattern, url);
  429. }
  430. @SuppressWarnings("unchecked")
  431. public static <T> T cast(Object obj) {
  432. return (T) obj;
  433. }
  434. /**
  435. * 数字左边补齐0,使之达到指定长度。注意,如果数字转换为字符串后,长度大于size,则只保留 最后size个字符。
  436. *
  437. * @param num 数字对象
  438. * @param size 字符串指定长度
  439. * @return 返回数字的字符串格式,该字符串为指定长度。
  440. */
  441. public static final String padl(final Number num, final int size) {
  442. return padl(num.toString(), size, '0');
  443. }
  444. /**
  445. * 字符串左补齐。如果原始字符串s长度大于size,则只保留最后size个字符。
  446. *
  447. * @param s 原始字符串
  448. * @param size 字符串指定长度
  449. * @param c 用于补齐的字符
  450. * @return 返回指定长度的字符串,由原字符串左补齐或截取得到。
  451. */
  452. public static final String padl(final String s, final int size, final char c) {
  453. final StringBuilder sb = new StringBuilder(size);
  454. if (s != null) {
  455. final int len = s.length();
  456. if (s.length() <= size) {
  457. for (int i = size - len; i > 0; i--) {
  458. sb.append(c);
  459. }
  460. sb.append(s);
  461. } else {
  462. return s.substring(len - size, len);
  463. }
  464. } else {
  465. for (int i = size; i > 0; i--) {
  466. sb.append(c);
  467. }
  468. }
  469. return sb.toString();
  470. }
  471. /**
  472. * 截取字符串最多12个字符
  473. *
  474. * @param input 原始字符串
  475. * @return 截取后的字符串,如果原始字符串长度小于等于12,则返回原始字符串
  476. */
  477. public static String truncateTo12Chars(String input) {
  478. if (input == null) {
  479. return "";
  480. }
  481. if (input.length() > 17) {
  482. return input.substring(0, 17) + "...";
  483. }
  484. return input;
  485. }
  486. /**
  487. * 获取文本中的img标签的src属性值
  488. *
  489. * @param htmlStr
  490. * @return
  491. */
  492. public static String[] getImgSrc(String htmlStr) {
  493. String old = htmlStr;
  494. String img = "";
  495. Pattern p_image;
  496. Matcher m_image;
  497. List<String> pics = new ArrayList<String>();
  498. p_image = Pattern.compile("<img.*src\\s*=\\s*(.*?)[^>]*?>", Pattern.CASE_INSENSITIVE);
  499. m_image = p_image.matcher(old.replace("\\", ""));
  500. while (m_image.find()) {
  501. img = m_image.group();
  502. Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
  503. while (m.find()) {
  504. if (m.group(1).indexOf("/profile/upload") != -1) {
  505. htmlStr = htmlStr.replace(m.group(1), m.group(1).substring(m.group(1).indexOf("/profile/upload"), m.group(1).length()));
  506. if (pics.size() <= 6) {
  507. pics.add(m.group(1).substring(m.group(1).indexOf("/profile/upload"), m.group(1).length()).trim());
  508. }
  509. } else {
  510. if (pics.size() <= 6) {
  511. pics.add(m.group(1).trim());
  512. }
  513. }
  514. }
  515. }
  516. return new String[]{pics.toString().replace("[", "").replace("]", "").replace(" ", ""), htmlStr};
  517. }
  518. /**
  519. * 从html中提取纯文本
  520. *
  521. * @param strHtml
  522. * @return
  523. */
  524. public static String StripHT(String strHtml) {
  525. String txtcontent = strHtml.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
  526. txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");//去除字符串中的空格,回车,换行符,制表符
  527. txtcontent = txtcontent.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "").replaceAll("\r\n", "").replaceAll(" ", "").trim();
  528. return txtcontent.substring(0, txtcontent.length() > 80 ? 100 : txtcontent.length());
  529. }
  530. public static String getRandomString(int count) {
  531. if (count > 0) {
  532. StringBuilder buf = new StringBuilder();
  533. Random rd = new Random();
  534. for (int i = 0; i < count; i++) {
  535. buf.append(rd.nextInt(10));
  536. }
  537. return buf.toString();
  538. } else {
  539. return "";
  540. }
  541. }
  542. public static String getBase64String(MultipartFile multiPartFile) throws IOException {
  543. byte[] fileBytes = multiPartFile.getBytes();
  544. String base64String = Base64.getEncoder().encodeToString(fileBytes);
  545. base64String = base64String.replaceAll("\r\n", "");
  546. return base64String;
  547. }
  548. public static String getFileName(String fileName) {
  549. return fileName.substring(0, fileName.lastIndexOf('.')) + ".jpg";
  550. }
  551. public static Long getId(String fileName) {
  552. return Long.parseLong(fileName.substring(fileName.lastIndexOf("/") + 1));
  553. }
  554. }