zoukankan      html  css  js  c++  java
  • Java按正则提取字符串

      在Java开发中,有时会遇到一些比较别扭的规则从字符串中提取子字符串,规则无疑是写正则表达式来表达了,那按照正则来提取子字符串就会用到java.util.regex包。

    java.util.regex是一个用正则表达式所订制的模式来对字符串进行匹配工作的类库包。 它包括两个类:Pattern和Matcher 。

    Pattern: 一个Pattern是一个正则表达式经编译后的表现模式。 

    Matcher: 一个Matcher对象是一个状态机器,它依据Pattern对象做为匹配模式对字符串展开匹配检查。

    首先一个Pattern实例订制了一个所用语法与PERL的类似的正则表达式经编译后的模式,然后一个Matcher实例在这个给定的Pattern实例的模式控制下进行字符串的匹配工作。 

     1 package com.founder.mrp.util;
     2 
     3 import java.util.regex.Matcher;
     4 import java.util.regex.Pattern;
     5 /**
     6  * 与String相关的工具方法集
     7  * @author Jimmy
     8  *
     9  */
    10 public class StringUtil {
    11 
    12     public static String getMatcher(String regex, String source) {  
    13         String result = "";  
    14         Pattern pattern = Pattern.compile(regex);  
    15         Matcher matcher = pattern.matcher(source);  
    16         while (matcher.find()) {  
    17             result = matcher.group(1);
    18         }  
    19         return result;  
    20     }  
    21     
    22     public static void main(String[] args) {
    23         String url = "http://172.12.1.123/test.txt";
    24         String regex = "(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})";
    25 //        String regex = "(\d{1,3}\.){1,3}(\d{1,3})";
    26         System.out.println(getMatcher(regex,url));
    27     }
    28     
    29 }

    参考资料:

    Pattern、Matcher: http://www.cnblogs.com/playing/archive/2011/03/15/1984943.html

    正则:http://deerchao.net/tutorials/regex/common.htm

  • 相关阅读:
    07月26日总结
    07月25日总结
    07月24日总结
    07月23日总结
    07月22日总结
    07月20日总结
    07月19日总结
    spinlock in c++11 based on atomic_flag std::memory_order_acquire
    c++ nullptr
    C++11 新特性: unordered_map 与 map 的对比
  • 原文地址:https://www.cnblogs.com/jimmy-c/p/4139664.html
Copyright © 2011-2022 走看看