Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26314627
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Java

2008-11-28 20:32:48

现在来讲一下正则表达式的实例吧:
实例一:
/**识别以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 += " 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");

  }
}
实例四:
package com.examples;
/**用正则表达式拆分java字符串数组的例子
*/
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      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;
  }
}
实例九:
package com.examples;
//正则表达式匹配电子邮件地址的java代码

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 parent 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);
     }
  }
实例十:


阅读(1113) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~