`
凯旋人生
  • 浏览: 62849 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

字符串处理利器--正则表达式(RegularExpressions)之一

    博客分类:
  • J2EE
阅读更多

单词:

  1. regular:[ˈreɡjulə]  有规律的, 定期的, 定时的
  2. Expression:[iksˈpreʃən] 表示式,公式
  3. Pattern:[ˈpætən] 型, 样式 花样, 图案
  4. Matcher: [ˈmætʃə] 匹配器;制榫机

一 用途:

  • 字符串的匹配
  • 字符串的查找
  • 字符串的替换

二 Java中的工具类:

  •  java.lang.String
  •  java.util.regex.Pattern   
  •  java.util.regex.Matcher

API:

.util.regex
Class Pattern

java.lang.Object
  java.util.regex.Pattern
All Implemented Interfaces:
Serializable

public final class Pattern
extends Object
implements Serializable

A compiled representation of a regular expression.

A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.

A typical invocation sequence is thus

 Pattern p = Pattern.compile("a*b");
 Matcher m = p.matcher("aaaaab");
 boolean b = m.matches();

A matches method is defined by this class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement

 boolean b = Pattern.matches("a*b", "aaaaab");

is equivalent to the three statements above, though for repeated matches it is less efficient since it does not allow the compiled pattern to be reused.

Instances of this class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.

Summary of regular-expression constructs

ConstructMatches   Characters   Character classes   Predefined character classes   POSIX character classes (US-ASCII only) <!---->   java.lang.Character classes (simple java character type)   Classes for Unicode blocks and categories   Boundary matchers   Greedy quantifiers   Reluctant quantifiers   Possessive quantifiers   Logical operators   Back references   Quotation <!---->   Special constructs (non-capturing)
x The character x
\\ The backslash character
\0n The character with octal value 0n (0 <= n <= 7)
\0nn The character with octal value 0nn (0 <= n <= 7)
\0mnn The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)
\xhh The character with hexadecimal value 0xhh
\uhhhh The character with hexadecimal value 0xhhhh
\t The tab character ('\u0009')
\n The newline (line feed) character ('\u000A')
\r The carriage-return character ('\u000D')
\f The form-feed character ('\u000C')
\a The alert (bell) character ('\u0007')
\e The escape character ('\u001B')
\cx The control character corresponding to x
[abc] a, b, or c (simple class)
[^abc] Any character except a, b, or c (negation)
[a-zA-Z] a through z or A through Z, inclusive (range)
[a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
[a-z&&[def]] d, e, or f (intersection)
[a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)
. Any character (may or may not match line terminators)
\d A digit: [0-9]
\D A non-digit: [^0-9]
\s A whitespace character: [ \t\n\x0B\f\r]
\S A non-whitespace character: [^\s]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]
\p{Lower} A lower-case alphabetic character: [a-z]
\p{Upper} An upper-case alphabetic character:[A-Z]
\p{ASCII} All ASCII:[\x00-\x7F]
\p{Alpha} An alphabetic character:[\p{Lower}\p{Upper}]
\p{Digit} A decimal digit: [0-9]
\p{Alnum} An alphanumeric character:[\p{Alpha}\p{Digit}]
\p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
\p{Graph} A visible character: [\p{Alnum}\p{Punct}]
\p{Print} A printable character: [\p{Graph}\x20]
\p{Blank} A space or a tab: [ \t]
\p{Cntrl} A control character: [\x00-\x1F\x7F]
\p{XDigit} A hexadecimal digit: [0-9a-fA-F]
\p{Space} A whitespace character: [ \t\n\x0B\f\r]
\p{javaLowerCase} Equivalent to java.lang.Character.isLowerCase()
\p{javaUpperCase} Equivalent to java.lang.Character.isUpperCase()
\p{javaWhitespace} Equivalent to java.lang.Character.isWhitespace()
\p{javaMirrored} Equivalent to java.lang.Character.isMirrored()
\p{InGreek} A character in the Greek block (simple block)
\p{Lu} An uppercase letter (simple category)
\p{Sc} A currency symbol
\P{InGreek} Any character except one in the Greek block (negation)
[\p{L}&&[^\p{Lu}]]  Any letter except an uppercase letter (subtraction)
^ The beginning of a line
$ The end of a line
\b A word boundary
\B A non-word boundary
\A The beginning of the input
\G The end of the previous match
\Z The end of the input but for the final terminator, if any
\z The end of the input
X? X, once or not at all
X* X, zero or more times
X+ X, one or more times
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}? X, exactly n times
X{n,}? X, at least n times
X{n,m}? X, at least n but not more than m times
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+ X, exactly n times
X{n,}+ X, at least n times
X{n,m}+ X, at least n but not more than m times
XY X followed by Y
X|Y Either X or Y
(X) X, as a capturing group
\n Whatever the nth capturing group matched
\ Nothing, but quotes the following character
\Q Nothing, but quotes all characters until \E
\E Nothing, but ends quoting started by \Q
(?:X) X, as a non-capturing group
(?idmsux-idmsux)  Nothing, but turns match flags on - off
(?idmsux-idmsux:X)   X, as a non-capturing group with the given flags on - off
(?=X) X, via zero-width positive lookahead
(?!X) X, via zero-width negative lookahead
(?<=X) X, via zero-width positive lookbehind
(?<!X) X, via zero-width negative lookbehind
(?>X) X, as an independent, non-capturing group

 

例子:

****************************************************
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // 简单的正则表达式例子
  //字符串是否是3个字符
 /* p("abc".matches("..."));
  //把字符串中的数字替换"-"
  p("a8729a".replaceAll("\\d", "-"));
  //匹配一个3个字符的字符串,并且每个字符都是a-z,编译是为了执行时会提升效率 
  Pattern p = Pattern.compile("[a-z]{3}");
  //public Matcher matcher(CharSequence input), String 实现了 CharSequence接口
  Matcher m = p.matcher("fgh");
  p(m.matches());
  p("fgh".matches("[a-z]{3}"));*/
  
 /* // 认识 .  *  +  ?
  //.匹配一个任意字符
  p("a".matches("."));
  //匹配字符"aa"
  p("aa".matches("aa"));
  //*匹配字符0个或多个a
  p("aaaa".matches("a*"));
  //+匹配字符 1个或多个
  p("aaaa".matches("a+"));
  //?匹配字符 0个或1个
  p("".matches("a?"));
  //?匹配字符 0个或1个
  p("a".matches("a?"));
  //{n}出现n次,{n,}出现n次以上,{n,m}出现n到m次
  p("214523145234532".matches("\\d{3,100}"));
  p("192.168.0.aaa".matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"));
  //[]是范围
  p("192".matches("[0-2][0-9][0-9]"));*/
  
  //范围 []
  //表示匹配[]中的一个字符  
 /* p("a".matches("[abc]"));
  //^abc  匹配abc外的一个字符
  p("a".matches("^abc"));
  //匹配
  p("a".matches("[a-zA-Z]"));
  //匹配a-z或 A-Z
  p("A".matches("[a-z]|[A-Z]"));
  //匹配a-z或 A-Z
  p("A".matches("[a-z[A-Z]]"));
  //匹配A-Z中的RFG中的之一
  p("R".matches("[A-Z&&[RFG]]"));*/
  
  /*//认识\s \w \d \
  //4个空白字符
  p("\n\r\t".matches("\\s{4}"));
  //非空白字符
  p(" ".matches("\\S"));
  //\w构成单词的字符
  p("a_8".matches("\\w{3}"));
  
  p("abc888&^%".matches("[a-z]{1,3}\\d+[&^#%]+"));
  //匹配一个\
  p("\\".matches("\\\\"));
  */
  
 /* //POSIX Style POSIX是一种UNIX标准
  p("a".matches("\\p{Lower}"));
  
  //boundary 边界匹配  ^在[]中是取反,[]外表示一行的开头
  
  p("hello sir".matches("^h.*"));
  p("hello sir".matches(".*ir$"));
  // \b是单词边界
  p("hello sir".matches("^h[a-z]{1,3}o\\b.*"));
  p("hellosir".matches("^h[a-z]{1,3}o\\b.*"));*/

  //whilte lines 空白行  (以空白字符开头并且不是换行符 )
  /*p(" \n".matches("^[\\s&&[^\\n]]*\\n$"));
  
  p("aaa 8888c".matches(".*\\d{4}."));
  p("aaa 8888c".matches(".*\\b\\d{4}."));
  p("aaa8888c".matches(".*\\d{4}."));
  p("aaa8888c".matches(".*\\b\\d{4}."));*/
  
  //email \w A word character: [a-zA-Z_0-9]   
  //[\\w[.-]]+  [a-zA-Z_0-9]或 .-  出现一次或多次
 /* p("asdfasdfsasdfasdf@asdfasdf.com".matches("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+"));
  */
  //matches find lookingAt
  /*
  Pattern p = Pattern.compile("\\d{3,5}");
  String s="123-34345-234-00";
  Matcher m = p.matcher(s);
  //匹配整个字串 "123-34345-234-00"
  p(m.matches());//匹配后引擎截取后"34345-234-00"
  //重新开始匹配
  m.reset();
  //匹配第一只串
  p(m.find());
  p(m.start()+"-"+m.end());
  p(m.find());
  p(m.start()+"-"+m.end());
  p(m.find());
  p(m.start()+"-"+m.end());
  p(m.find());
  //如果找不到会报错
  p(m.start()+"-"+m.end());
  //每次都重头匹配 lookingAt()
  p(m.lookingAt());
  p(m.lookingAt());
  p(m.lookingAt());
  p(m.lookingAt());
  */
  
 /* //replacement 把所含有java(无论大小写的,单数替换为java 偶数替换为JAVA
  Pattern p = Pattern.compile("java",Pattern.CASE_INSENSITIVE);
  Matcher m = p.matcher("java Java JAVa JaVa IloveJAVA you hateJava asdf");
  StringBuffer buf = new StringBuffer();
  int i=0;
  while(m.find()){
   //m.guoup()匹配的子串
   //p(m.group());
   i++;
   if(i%2==0){
    //找到子串放到buf中,并用后面的替换
    m.appendReplacement(buf, "java");
   }else
   {
    m.appendReplacement(buf, "JAVA");
   }
   
  }
  m.appendTail(buf);
  p(buf);*/
  
  //group
  Pattern p = Pattern.compile("(\\d{3,5})([a-z]{2})");
  String s ="123aa-34345bb-234cc-00";
  Matcher m = p.matcher(s);
  while(m.find())
  {
   //整个大组
   p(m.group());
  }
  
  m.reset();
  while(m.find())
  {
   //第1小组
   p(m.group(1));
  }

  m.reset();
  while(m.find())
  {
   //第2小组
   p(m.group(2));
  }  
 }
 
 

 
 
 public static void p (Object o)
 {
  System.out.println(o);
 }
 
 

****************************************************

 

 

抓取文件中Email地址的程序代码

***************************************************************

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;


public class EmailSpider {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
   BufferedReader br= new BufferedReader(new FileReader("c:\\email.htm"));
   String line="";
   while((line=br.readLine())!=null)
   {
     parse(line); 
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 private static void parse(String line) {
  // TODO Auto-generated method stub
  Pattern p =Pattern.compile("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+");
  Matcher m = p.matcher(line);
  while(m.find())
  {
   System.out.println(m.group());
  }
  
//  Matcher m =
 }

}

 


*****************************************************************

 

分享到:
评论

相关推荐

    C#字符串和正则表达式参考手册.zip

    在C#中,字符串是处理文本数据的基础,而正则表达式则是进行复杂文本匹配和处理的利器。本手册深入浅出地介绍了这两个重要概念,旨在帮助开发者提升对文本处理的能力。 一、C#字符串 1. 字符串基本概念:C#中的字符...

    强大的正则表达式生成工具 C#版

    正则表达式是一种强大的文本处理工具,用于在字符串中进行模式匹配和搜索替换操作。C#作为.NET框架的一部分,提供了全面支持正则表达式的类库,使得开发人员能够方便地利用正则表达式进行复杂的文本处理任务。在这个...

    正则表达式案例学习文档

    正则表达式是一种强大的文本处理工具,用于匹配、查找、替换和分析字符串模式。它在编程语言中广泛应用,包括C#。本教程旨在通过案例学习,帮助你提升至正则表达式的中级水平。 首先,我们要了解正则表达式的基础...

    正则表达式利器

    正则表达式(Regular Expression,简称regex)是编程领域中的一种强大的文本处理工具,它能够高效地进行字符串匹配、查找、替换以及提取等操作。在IT行业中,掌握正则表达式是提高工作效率的关键技能之一,尤其对于...

    ASP_NET正则表达式

    总结,ASP.NET正则表达式是开发者手中的利器,能够高效地处理字符串数据。正确理解和运用正则表达式,可以极大地提高代码质量和效率。结合C#、ASP.NET、SQL和DBA的知识,开发者可以构建出更健壮、更安全的Web应用...

    .net正则表达式大全

    .NET框架提供了`System.Text.RegularExpressions`命名空间下的`Regex`类,支持复杂的正则表达式功能。本文将详细解析一组广泛使用的正则表达式,涵盖数字验证、字符串格式检查、电子邮件与URL验证等多个方面,旨在...

    正则表达式PPT演示稿

    正则表达式是一种强大的文本处理工具,用于在字符串中搜索、查找、替换和解析符合特定模式的文本。它由普通字符和元字符组成,形成一个模式,能够高效地解决多种与文本相关的任务。正则表达式是编程语言中的一个重要...

    C#字符串和正则表达式参考手册

    正则表达式是一种强大的文本处理工具,用于匹配、查找、替换和提取字符串模式。C#通过`System.Text.RegularExpressions`命名空间提供了对正则表达式的支持。以下是正则表达式的关键概念: 1. **基础元素**:如点`.`...

    .net正则表达式测试台

    正则表达式是编程领域中用于处理字符串的强大工具,广泛应用于数据验证、文本提取、搜索替换等多个场景。在.NET框架中,正则表达式提供了丰富的功能和高度的灵活性。本文将详细探讨.NET正则表达式测试台这款开发工具...

    很好的正则表达式学习资料

    正则表达式(Regular Expression,简称regex)是...总之,正则表达式是处理字符串的利器,掌握好正则表达式将极大地提高你在文本处理中的效率。通过不断地练习和应用,你将能够灵活运用正则表达式解决各种复杂的问题。

    C#正则表达式手册

    在C#中,`System.Text.RegularExpressions`命名空间包含了处理正则表达式的主要类,如`Regex`。这个类提供了许多静态方法,如`Match`, `Matches`, `Replace`, `Split`等,用于执行正则表达式操作。 1. **创建正则...

    Delphi+正则表达式

    在编程领域,正则表达式(Regular Expression)是一种强大的文本处理工具,用于匹配、查找、替换和提取字符串模式。在Delphi编程环境中,开发者可以利用正则表达式进行高效的数据处理和验证工作。本篇文章将深入探讨...

    Regilator

    在.NET Framework中,正则表达式功能由`System.Text.RegularExpressions`命名空间下的类库提供,如`Regex`类。然而,正则表达式的语法相当复杂,编写和调试过程可能会遇到很多挑战,这就凸显了Regilator的价值。 ...

    Regular.Expressions.Cookbook.2009

    正则表达式是一种模式匹配语言,允许用户用一种简洁的方式来描述一组字符串。在编程中,它们常被用来验证输入、提取信息或进行复杂的文本处理。例如,你可以用正则表达式来检查一个电子邮件地址的格式是否正确,或者...

    sap-abap培训讲义资源分享

    在SAP ABAP开发中,正则表达式(Regular Expressions)是一种强大的文本处理工具,广泛应用于数据验证、信息提取和值的规范化等场景。在本篇内容中,我们将深入探讨如何在ABAP环境中利用正则表达式进行高效的数据...

    Regular Expressions

    正则表达式(Regular Expressions)是编程领域中一种强大的文本处理工具,它使用特定的语法来匹配、查找、替换或验证字符串模式。在IT行业中,掌握正则表达式是解决许多文本处理问题的关键,特别是在数据提取、数据...

    delphi TPerlRegEx 正则类

    在Delphi编程环境中,`TPerlRegEx`是`RegularExpressions`单元的一部分,允许开发者进行复杂的文本处理和数据提取。 ### 1. `TPerlRegEx`的基本用法 `TPerlRegEx`类的实例化通常包括以下步骤: 1. 创建`TPerlRegEx...

    orcl_reg.zip_oracle10G

    正则表达式是文本处理和数据提取中的利器,能够帮助我们高效地进行模式匹配、查找、替换等一系列操作。本文将围绕Oracle 10g中的正则表达式展开详细阐述,旨在帮助读者深入理解和掌握这一强大的工具。 首先,让我们...

    TPerlRegEx for pcre 8.20

    在软件开发中,正则表达式是一种强大的文本处理工具,它能帮助我们进行复杂的文本匹配、查找、替换等操作。在Delphi编程环境中,TPerlRegEx是用于封装Perl兼容正则表达式库(PCRE)的一个组件,它为Delphi开发者提供...

    regexpal3.1.1

    1. **实时测试**:Regexpal提供了一个实时的测试区域,用户可以即时看到正则表达式与目标字符串的匹配情况,便于快速调试和验证正则表达式的正确性。 2. **语法高亮**:代码区域的语法高亮有助于用户更好地理解正则...

Global site tag (gtag.js) - Google Analytics