`

java正则表达式简介和split详细介绍

    博客分类:
  • Java
阅读更多

 

java正则表达式

Java的正则表达式是由java.util.regex的Pattern和Matcher类实现的。Pattern对象表示经编译的正则表达式。静态的compile( )方法负责将表示正则表达式的字符串编译成Pattern对象。只要给Pattern的matcher( )方法送一个字符串就能获取一个Matcher对象。此外,Pattern还有一个能快速判断能否在input里面找到regex的staticboolean matches(?regex, ?input)方法以及以及能返回String数组的split( )方法,它能用regex把字符串分割开来。

Matcher的方法来查询匹配的结果了。

boolean matches()

boolean lookingAt()

boolean find()

boolean find(int start)

matches( )的前提是Pattern匹配整个字符串,而lookingAt( )的意思是Pattern匹配字符串的开头。find( )像一个迭代器,从头到尾扫描一遍字符串。上次匹配的最后将是下次匹配的开始。第二个find( )是带int参数的,正如你所看到的,它会告诉方法从哪里开始找——即从参数位置开始查找。这上面的方法都会改变匹配器开始匹配的起始位置。lookingAt( )和matches( ),只有在字符串与正则表达式一开始就相匹配的情况下才能返回true。matches( )成功的前提是正则表达式与字符串完全匹配,而lookingAt( )成功的前提是,字符串的开始部分与正则表达式相匹配。上面的几个方法都会改变匹配的一些属性。通过看源码知道Mather有下面这些属性(不止这些,这里没有贴出全部)

 

 /**
     * The storage used by groups. They may contain invalid values if
     * a group was skipped during the matching.
     */
    int[] groups;

    /**
     * The range within the sequence that is to be matched. Anchors
     * will match at these "hard" boundaries. Changing the region
     * changes these values.
     */
    int from, to;

    /**
     * Lookbehind uses this value to ensure that the subexpression
     * match ends at the point where the lookbehind was encountered.
     */
    int lookbehindTo;

    /**
     * The original string being matched.
     */
    CharSequence text;

    /**
     * Matcher state used by the last node. NOANCHOR is used when a
     * match does not have to consume all of the input. ENDANCHOR is
     * the mode used for matching all the input.
     */
    static final int ENDANCHOR = 1;
    static final int NOANCHOR = 0;
    int acceptMode = NOANCHOR;

    /**
     * The range of string that last matched the pattern. If the last
     * match failed then first is -1; last initially holds 0 then it
     * holds the index of the end of the last match (which is where the
     * next search starts).
     */
    int first = -1, last = 0;
 

 

上面的方法都会改变first,last,from,to等这些属性。Matcher的start()返回的实际上是first,end()方法换回的是last。如果first为-1是你去调用start方法会出现异常:throw new IllegalStateException("No match available");

 

下面这段代码是实例:

 

 

Matcher m = Pattern.compile("\\w+").matcher(
				"Evening is full of the linnet's wings");
		System.out.println(m.lookingAt()+"  "+m.start()+":"+m.end());
		Matcher mm = Pattern.compile("\\w+").matcher(
		"Evening");
		System.out.println(mm.matches());
		mm.reset();
		System.out.println(mm.find()+":"+m.start()+":"+m.end());
		while(mm.find()){
			System.out.println(mm.start()+mm.end());
		}
		while (m.find()){
			System.out.println(m.start()+":"+m.end());
			System.out.println(m.group());
		}
 

得到结果为:

true  0:7

true

true:0:7

8:10

is

11:15

full

16:18

of

19:22

the

23:29

linnet

30:31

s

32:37

wings

 

 

现在看正则表达式的应用,像String类中有split(reg,limit)方法,这个方法实际上是又调用了Pattern.compile(regex).split(str, n) 

我们看split应用实例:

 

String newStr = "AaaaA";
String[] bb = p.split(newStr);
System.out.println(Arrays.toString(bb));
 

这样会得到一个很难理解的结果:[, A, , A]

这样很奇怪怎么是这样呢。一般人会理解为[A,A]。其实上面的相当与下面的

 

String newStr = "AaaaA";
Pattern p = Pattern.compile("a*");
Matcher m =p.matcher(newStr);
int index=0;
List<String> list = new ArrayList<String>();
while(m.find()){
	System.out.println(m.start()+":"+m.end());
	String str = newStr.substring(index, m.start());
	System.out.println(str);
	list.add(str);
	index=m.end();
}
System.out.println(Arrays.toString(list.toArray()));

 通过看源码你会发现split的实现其实和上面是同一种方式的。只是写得更复杂,而没那么简单而已。这样我们就很容易理解了。所以要得到[A,A]的结果,只需改变正则表达式为"a+"即可。

 写道
int index = 0;
boolean matchLimited = limit > 0;
ArrayList<String> matchList = new ArrayList<String>();
Matcher m = matcher(input);

// Add segments before each match found
while(m.find()) {
if (!matchLimited || matchList.size() < limit - 1) {
String match = input.subSequence(index, m.start()).toString();
matchList.add(match);
index = m.end();
} else if (matchList.size() == limit - 1) { // last one
String match = input.subSequence(index,
input.length()).toString();
matchList.add(match);
index = m.end();
}
}

// If no match was found, return this
if (index == 0)
return new String[] {input.toString()};

// Add remaining segment
if (!matchLimited || matchList.size() < limit)
matchList.add(input.subSequence(index, input.length()).toString());

// Construct result
int resultSize = matchList.size();
if (limit == 0)
while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
resultSize--;
String[] result = new String[resultSize];
return matchList.subList(0, resultSize).toArray(result);
 

随便提一下java正则表达式和javascript还是有点小区别的。javascript中这样写

 

var s ="AaaaA"

var patt=/a*/

console.log(s.split(patt))

得到的结果也是:

 

 

["A", "A"]

 

 

 

分享到:
评论

相关推荐

    java-正则表达式-正则表达式元素介绍

    正则表达式主要配合以下方法使用 匹配 string.matches() 分割 string.split() 替换 string.replaceAll()

    java正则表达式匹配全角空格

    split函数按照空格拆分,兼容全角空格、半角空格

    Java正则表达式学习教程

    Java正则表达式和Perl的是最为相似的。 Java正则表达式的类在 java.util.regex 包中,包括三个类:Pattern,Matcher 和 PatternSyntaxException。 Pattern对象是正则表达式的已编译版本。他没有任何公共构造器,我们...

    java 正则表达式

    JAVA正则表达式语法(转)正则表达式语法正则表达式是一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为“元字符”)。模式描述在搜索文本时要匹配的一个或多个字符串。正则表达式示例表达式 ...

    精通正则表达式~~~

    第3章:正则表达式的特性和流派概览.... 83 在正则的世界中漫步... 85 正则表达式的起源... 85 最初印象... 91 正则表达式的注意事项和处理方式... 93 集成式处理... 94 程序式处理和面向对象式处理... 95 ...

    正则表达式

    1.2. 正则表达式简介 1、 正则表达式是一个强大的字符串处理工具,可以对字符串进行、查找、提取、分割、替换等操作。它简单而且实用,是一个用于匹配字符串的模板,我们定义的任意的一个字符串都可以看成是一个正则...

    Java中使用正则表达式处理文本数据

    本文将介绍如何在Java中使用正则表达式来处理文本数据。正则表达式就是一个字符串,但和普通的字符串不同的是,正则表达式是对一组相似字符串的抽象,如下面的几个字符串: a98b c0912d c10b a12345678d ab ...

    Java正则表达式之split()方法实例详解

    主要介绍了Java正则表达式之split()方法,结合实例形式较为详细的分析了split方法的功能、使用方法及相关注意事项,需要的朋友可以参考下

    一个java正则表达式工具类源代码.zip(内含Regexp.java文件)

    * Summary of regular-expression constructs 正则表达式结构简介: * Construct Matches * Characters 字符: * x The character x x 字符 x * \\ The ...

    javascript用正则表达式把1234567890替换为abcdefghij

    您可能感兴趣的文章:JavaScript利用正则表达式替换字符串中的内容使用JS正则表达式 替换括号,尖括号等JS使用正则表达式过滤多个词语并替换为相同长度星号的方法JS使用正则表达式实现关键字替换加粗功能示例js正则...

    String字符串匹配javascript 正则表达式

    在JavaScript代码中使用正则表达式进行模式匹配经常会用到String对象和RegExp对象的一些方法,例如replace、match、search等方法,下面所述是对相关方法使用的总结,需要的朋友参考下。 String对象中支持正则表达式...

    javascript使用正则表达式实现去掉空格之后的字符

    现在来说说用正则表达式怎么实现. 思路:获取到字符串中的空格,然后把空格及空格后的字符全部替换为空. 获取空格的正则为\s 实践: 代码如下: var date = “2015-12-26 15:22:00”; console.log(date.replace(/\s*/g,...

    Java中正则表达式split()特殊符号使用详解

    主要介绍了Java中正则表达式split()特殊符号使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

    Java编码规范总结

    修复建议:String的split方法传递的参数是正则表达式,正则表达式本身用到的字符需要转义,如:句点符号“.”,美元符号“$”,乘方符号“^”,大括号“{}”,方括号“[]”,圆括号“()” ,竖线“|”,星号“*”,...

    JAVA中正则表达式匹配,替换,查找,切割的方法

    本文主要给大家介绍java正则表达式匹配,替换,查找,切割的方法,查找是用string类中的split(),字符串中的替换是replace(),感兴趣的朋友一起来学习吧

    Android中Split()字符串分割特殊用法案例详解

    split()分割字符串 1.不同环境下的区分 Java:分割字符串不能写成split(“$”...| 在正则表达式中是个已经被使用的特殊符号(”.”、”|”、”^”等字符) 所以想要使用 | ,必须用 \ 来进行转义,而在java字符串中,\

    JAVA:使用Pattern移除List相应元素(如去除带数字的元素),附上java Pattern相关正则表达式

    addAll(Arrays.asList(puyuma0216puyuma.split()));//将数组转化为list add(puyuma); add(0216); add(puyuma0216) ; } }; System.out.println(list初始数据: + list); Pattern pattern = Pattern.compile(\\d)...

    Java-PHP-C#

    此外,JavaScript这种客户端的脚本语言也提供了对正则表达式的支持,现在正则表达式已经成为了一个通用的概念和工具,被各类技术人员所广泛使用。 在某个Linux网站上面有这样的话:"如果你问一下Linux爱好者最喜欢...

    java解析出url请求的路径和参数键值对类(解析出url请求的路径,包括页面)

    解析url,本想用正则表达式处理,但正则表达式速度较慢。用split处理一下就可以了

Global site tag (gtag.js) - Google Analytics