`
xingcxb
  • 浏览: 46738 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

JAVA正则表达式实例

 
阅读更多
实例一:
/**识别以255开头的IP值 * */
package com.examples;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PositiveLookaheadExample {
    public static void main(String[] args) {
        /** 1.编译你的正则表达式到Pattern的实例中.
            2.使用Pattern对象创建Matcher对象.
            3.使用Matcher对象去控制或操纵这个字符序列.
         * */
        String regex = "(?=^255).*";//定义正则表达式
        Pattern pattern = Pattern.compile(regex);
        String candidate = "255.0.0.1";//待匹配的字符串
        Matcher matcher = pattern.matcher(candidate);
        String ip = "not found";
        if (matcher.find())//下面就是用match对象来操纵字符序列
          ip = matcher.group();
        String msg = "ip: " + ip;
        System.out.println(msg);
    }
}


实例二:
/**java用正则表达式查找字符串的例子*/
package com.examples;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PositiveLookBehindExample {
  public static void main(String args[]) throws Exception {
    String regex = "(?<=http://)\\S+";//问题是如何来写这个正则表达式呢?
    Pattern pattern = Pattern.compile(regex);
    String candidate = "你能从这个字符串里找到网址吗";
    candidate += "http://www.100jq.com. There, ";
    candidate += "you can find some Java examples.";
    Matcher matcher = pattern.matcher(candidate);
    while (matcher.find()) {
      String msg = ":" + matcher.group() + ":";
      System.out.println(msg);
    }
  }
}


实例三:
/**从命令行输入一个字符串与给定的正则表达式匹配*/
package com.examples;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RE_QnotU_Args {
  public static void main(String[] argv) {
    String patt = "^Q[^u]\\d+\\.";
    Pattern r = Pattern.compile(patt);
      Matcher m = r.matcher("RE_QnotU_Args");
      boolean found = m.lookingAt();
      System.out.println(patt + (found ? " matches " : " doesn't match ") + "RE_QnotU_Args");
  }
}


实例四:
/**用正则表达式拆分java字符串数组的例子**/
package com.examples;
import java.util.regex.*;
public class Split {
  public static void main(String[] args) {
    String[] x =
      Pattern.compile("ian").split(
        "the darwinian devonian explodian chicken");
    for (int i=0; i<x.length; i++) {
      System.out.println(i + " \"" + x[i] + "\"");
    }
  }
}


实例五:
//将正则表达式的查找方法封装成一个类的代码
package com.examples;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public final class RegexTestHarness2 {
  private static String REGEX;
  private static String INPUT;
  private static BufferedReader br;
  private static Pattern pattern;
  private static Matcher matcher;
  private static boolean found;

  public static void main(String[] argv) {
    initResources();
    processTest();
    closeResources();
  }

  private static void initResources() {
    try {
      br = new BufferedReader(new FileReader("regex.txt"));
    } catch (FileNotFoundException fnfe) {
      System.out
          .println("Cannot locate input file! " + fnfe.getMessage());
      System.exit(0);
    }
    try {
      REGEX = br.readLine();
      INPUT = br.readLine();
    } catch (IOException ioe) {
    }
    try {
      pattern = Pattern.compile(REGEX);
      matcher = pattern.matcher(INPUT);
    } catch (PatternSyntaxException pse) {
      System.out
          .println("There is a problem with the regular expression!");
      System.out.println("The pattern in question is: "
          + pse.getPattern());
      System.out.println("The description is: " + pse.getDescription());
      System.out.println("The message is: " + pse.getMessage());
      System.out.println("The index is: " + pse.getIndex());
      System.exit(0);
    }

    System.out.println("Current REGEX is: " + REGEX);
    System.out.println("Current INPUT is: " + INPUT);
  }

  private static void processTest() {
    while (matcher.find()) {
      System.out.println("I found the text \"" + matcher.group()
          + "\" starting at index " + matcher.start()
          + " and ending at index " + matcher.end() + ".");
      found = true;
    }
    if (!found) {
      System.out.println("No match found.");
    }
  }

  private static void closeResources() {
    try {
      br.close();
    } catch (IOException ioe) {
    }
  }
}



实例六:
//正则表达式查询
package com.examples;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class MatcherTest {

  private static final String REGEX = \\bdog\\b;
  private static final String INPUT = "dog dog dog doggie dogg";

  public static void main(String[] argv) {
    Pattern p = Pattern.compile(REGEX);
    Matcher m = p.matcher(INPUT); // get a matcher object
    int count = 0;
    while (m.find()) {
      count++;
      System.out.println("Match number " + count);
      System.out.println("start(): " + m.start());
      System.out.println("end(): " + m.end());
    }
  }
}

实例7:
//正则表达式匹配邮政编码
package com.examples;
public class MatchZipCodes {
  public static void main(String args[]) {
    isZipValid("45643-4443");
    isZipValid("45643");
    isZipValid("443");
    isZipValid("45643-44435");
    isZipValid("45643 44435");
  }
  public static boolean isZipValid(String zip) {
    boolean retval = false;
    String zipCodePattern = "\\d{5}(-\\d{4})?";
    retval = zip.matches(zipCodePattern);
    String msg = "NO MATCH: pattern:" + zip + "\r\n             regex: " + zipCodePattern;

    if (retval) {
      msg = "MATCH   : pattern:" + zip + "\r\n             regex: " + zipCodePattern;
    }

    System.out.println(msg + "\r\n");
    return retval;
  }
}


实例八:
//正则表达式匹配电话号码
package com.examples;
public class MatchPhoneNumber {
  public static void main(String args[]) {
    isPhoneValid("1-999-585-4009");
    isPhoneValid("999-585-4009");
    isPhoneValid("1-585-4009");
    isPhoneValid("585-4009");
    isPhoneValid("1.999-585-4009");
    isPhoneValid("999 585-4009");
    isPhoneValid("1 585 4009");
    isPhoneValid("111-Java2s");
  }
  public static boolean isPhoneValid(String phone) {
    boolean retval = false;
    String phoneNumberPattern = "(\\d-)?(\\d{3}-)?\\d{3}-\\d{4}";
    retval = phone.matches(phoneNumberPattern);
    String msg = "NO MATCH: pattern:" + phone + "\r\n regex: " + phoneNumberPattern;

    if (retval) {
      msg = " MATCH: pattern:" + phone + "\r\n             regex: " + phoneNumberPattern;
    }
    System.out.println(msg + "\r\n");
    return retval;
  }
}


实例九:
//正则表达式匹配电子邮件地址的java代码

package com.examples;
public class SubStringDemo {
     public static void main(String[] args) {
        String s = "suraj.gupta@yahoo.com"; // email id in a String
        int IndexOf = s.indexOf("@"); // returns an integer which tells the position of this substring "@" in the String "suraj.gupta@yahoo.com"
        String domainName = s.substring(IndexOf); //prints the String after that index
        System.out.println("Taking Domain name from an email id "+domainName);
     }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics