RegEx (Regular Expressions)

1 minute read

A good website: Vogella.com

Basic

^once

^ represent to match string begin with it;
String once upon a time meet this situation;
String There once upon a time is not meet;

bucket$

$ represent to match string End with it;
String Who kept all of this cash in a bucket meet this situation;
String buckets is not meet;

We can use ^ and $ together to match specific value, for example: ^bus$ only match “bus”;

*String Once is matching There once was a man from New York, because Once only represent 0-n-c-e characters, it is same if we use numbers. *

But if we want to find Space or Enter, we need using \ : \n ;

^\n represent begin with space

Character cluster

1

[a-z] //匹配所有的小写字母 
[A-Z] //匹配所有的大写字母 
[a-zA-Z] //匹配所有的字母 
[0-9] //匹配所有的数字 
[0-9\.\-] //匹配所有的数字,句号和减号 
[ \f\r\t\n] //匹配所有的白字符

For Example: we want to find a string begin with number and end with word;

^[a-z][0-9]$ is matching “z2”, “t6”, “t4”, but not matching “wer1”, “w23”, “e2r4”;

2

^ also have different meaning as “NOT” in [ ]

^[^0-9][0-9]$ is matching “%3”, “s5”, but not matching “12”, “34”;

3

[^a-z] //除了小写字母以外的所有字符 
[^\\\/\^] //除了(\)(/)(^)之外的所有字符 
[^\"\'] //除了双引号(")和单引号(')之外的所有字符

Repeated Character

^[a-zA-Z_]$: all word and “_”;

^a{4}$: find “aaaa”

^a{2,4}$: find “aa”, “aaa”, “aaaa”

^a{2,}$: find more than “aa”, such as “aaa”, “aaaaaaaaa”

^[a-zA-Z0-9_]{1,}$      // 所有包含一个以上的字母、数字或下划线的字符串 
^[1-9][0-9]{0,}$        // 所有的正整数 
^\-{0,1}[0-9]{1,}$      // 所有的整数 
^[-]?[0-9]+\.?[0-9]+$   // 所有的浮点数

最后一个例子不太好理解,是吗?这么看吧:以一个可选的负号 ([-]?) 开头 (^)、跟着1个或更多的数字([0-9]+)、和一个小数点(.)再跟上1个或多个数字([0-9]+),并且后面没有其他任何东西($)。下面你将知道能够使用的更为简单的方法。

特殊字符 ? 与 {0,1} 是相等的,它们都代表着: 0个或1个前面的内容 或 前面的内容是可选的 。所以刚才的例子可以简化为:

^\-?[0-9]{1,}\.?[0-9]{1,}$

特殊字符 * 与 {0,} 是相等的,它们都代表着 0 个或多个前面的内容 。最后,字符 + 与 {1,} 是相等的,表示 1 个或多个前面的内容 ,所以上面的4个例子可以写成:

^[a-zA-Z0-9_]+$      // 所有包含一个以上的字母、数字或下划线的字符串 
^[1-9][0-9]*$        // 所有的正整数 
^\-?[0-9]+$          // 所有的整数 
^[-]?[0-9]+(\.[0-9]+)?$ // 所有的浮点数

有趣的双反斜杠(\)
在Java字符串中,存在诸如\n,\r等转义字符,而反斜杠\自己本身也是转义字符,所以在Java字符串中,要输出\,需要写两个\,即\。

而正则表达式也需要匹配转义字符,故正则表达式要匹配一个\的时候,也需要写两个\。

所以,在Java中使用正则表达式,要匹配一个\,需要写四个\。

Updated: