Guest User

Untitled

a guest
Nov 13th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5.  
  6. /**
  7. * @author <a href="mailto:strongant1994@gmail.com">strongant</a>
  8. * @since 2017/8/20
  9. */
  10. public class QuoteTypeMatch {
  11. public static void main(String[] args) {
  12. String msg = "PerformanceManager{第1个中括号}Product{第2个中括号}<{第3个中括号}79~";
  13. List<String> list = extractMessageByRegular(msg, "{", "}");
  14. for (int i = 0; i < list.size(); i++) {
  15. System.out.println(i + "-->" + list.get(i));
  16. }
  17. }
  18.  
  19. /**
  20. * 使用正则表达式提取中括号中的内容
  21. *
  22. * @param msg
  23. * @return
  24. */
  25. public static List<String> extractMessageByRegular(String msg, String quoteTypeLeft, String quoteTypeRight) {
  26.  
  27. if (null == msg || msg.length() == 0) {
  28. throw new IllegalArgumentException("指定的查找字符串不能为空!");
  29. }
  30.  
  31. if (null == quoteTypeLeft || quoteTypeLeft.length() == 0) {
  32. throw new IllegalArgumentException("左边符号不能为空!");
  33. }
  34.  
  35.  
  36. if (null == quoteTypeRight || quoteTypeRight.length() == 0) {
  37. throw new IllegalArgumentException("右边符号不能为空!");
  38. }
  39. List<String> list = new ArrayList<>();
  40. Pattern p = Pattern.compile(String.format("\\%s.*?\\%s", quoteTypeLeft, quoteTypeRight));
  41. Matcher m = p.matcher(msg);
  42. while (m.find()) {
  43. list.add(m.group().substring(1, m.group().length() - 1));
  44. }
  45. return list;
  46. }
  47. }
Add Comment
Please, Sign In to add comment