Skip to content

Latest commit

 

History

History
590 lines (448 loc) · 33.6 KB

正则表达式.md

File metadata and controls

590 lines (448 loc) · 33.6 KB

正则表达式

表达式

表达式 描述
^ 开头,在[]、()中表示非该字符
& 结尾
\b 单词边界
\B 非单词边界
\ 转义,特殊字符需要转义(java Pattern.compile方法中为字符串,需要再使用一个 / 对转义字符 / 进行转义。。)
. 除换行符\n的任意字符
\d 数字
\D 非数字(字母、符号)
\s 任意空白字符,等价于[ \f\n\r\t\v]
\S 任意非空白字符[^ \f\n\r\t\v]
\w 字母、数字、下划线
\W 非字母、数字、下划线
\n 换行符
[\s\S]* 包括\n的任意字符(.无法匹配\n)
[a-zA-Z] 字母
[as1] a/s/1三个字母
[0-9] 0-9
(a|A) a或A
['"] 匹配单引号或双引号
[^'"] 匹配非单双引号
(test1|test2) 匹配test1 或 test2
((?!test1|test2).) 匹配非test1 和非 test2
\1 第一个分组中的内容,\2、\3...

转义字符

匹配{ } [ ] / \ + * . $^ | ?时需要在前面添加转义符""表示转义

限定符

表达式 描述
* 出现任意次数
+ 至少一次
? 出现0次或1次
{1,} 至少一次
{1} 出现一次
{1,3} 出现1-3次

贪婪匹配

*?

出现任意次数 非贪婪匹配

*?style 匹配到第一个style

+?

出现至少一次 非贪婪匹配

匹配1234
\d+ 	一个分组:1234
\d+? 	四个分组:1,2,3,4

保留分组

保留分组可在匹配结果/替换使用

()

保留分组

使用分组

java

matcher.group(1)

js replace

$1

java replaceAll

$1

(?:)

(?:img|IMG)

非保留分组

前瞻后顾

限定字符前后的内容,且不消耗字符

前瞻(Positive Lookahead):(?=),限定字符前面的内容

负前瞻(Negative Lookahead):(?!),限定不在字符前面的内容

后顾(Positive Lookbehind):(?<=),限定字符后面的内容

负后顾(Negative Lookbehind):(?<!),限定不在字符后面的内容

'aa11bb22cc'.replace(/(?<=aa)\d+(?=bb)/g, '--')
"aa--bb22cc"
'aa11bb22cc'.replace(/aa\d+bb/g, '--')
"--22cc"

包含英文和数字最少8位

^(?=.*[0-9])(?=.*[a-zA-Z])(.{8,})$

包含edit和data

(?=.*edit)(?=.*data)(.*)

后顾写在最前面,说明在整个字符串包含即可,可用于密码校验

替换链接中的域名端口

'rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov'.replace(/(?<=:\/\/).*?(?=\/)/g, '127.0.0.1:10008')

匹配两个字符串中间的内容

(?<=connect to database success)[\s\S]*?(?=connection close success)

替换部分文件的扩展名

filePath.replaceAll("(?<=\\.)(doc|docx|xls|xlsx|ppt|pptx)$", "pdf")

标志位

g:global,选择所有的匹配,否则只选择第一个匹配

m:multiline,分别处理每一行,如匹配每行末的数字:\d+$,否则所有文本将被视为一行

i:case insensitive,大小写不敏感

'1234'.replace(/\d/g, '-')

实例

包含bug的字符
.*bug.*
不包含
# 不包含\</tr>的(不包含\n的)任意字符
((?!</tr>).)*?
# 不包含\</tr>的(包含\n)的任意字符
((?!</tr>)[\s\S])*?

# vscode 中删除console中不包含INFO的行(不知道为何此时\s\S不包含\n。。)
^((?!INFO)[\s\S\n])*$
^((?!LoginController:(89|145))[\s\S\n])*$
在html中匹配img标签
<img.*src\\s*=\\s*[^>]*?>
满足几个表达式中的一个
(^127.0,.*|.*,127.0,.*|.*,127.0$|127.0)
去重
'tteeestt1112'.replace(/(.*)\1+/g, '$1')

匹配重复内容:(.*)\1+

在html中的特定img标签中加入样式
matchContent = matchContent.replaceAll("(<(?:img|IMG)[^>]*?style\\s*=\\s*['\"][^'\"]*)(['\"][^>]*?src\\s*=\\s*['\"]" + tp.url + "['\"](?:(?!style|>).)*>)", "$1 " + MATCH_PIC_STYLE + " $2")
    		.replaceAll("(<(?:img|IMG)(?:(?!style|>).)*?src\\s*=\\s*['\"]" + tp.url + "['\"][^>]*?style\\s*=\\s*['\"][^'\"]*)(['\"][^>]*>)", "$1 " + MATCH_PIC_STYLE + " $2")
    		.replaceAll("(<(?:img|IMG)(?:(?!style|>).)*?)(src\\s*=\\s*['\"]" + tp.url + "['\"](?:(?!style|>).)*>)", "$1 style=\"" + MATCH_PIC_STYLE + "\" $2");
使用 img 和 src 匹配标签

三种情况

  1. style 在 src 右边
  2. style 在 src 左边
  3. 没有style
(?:img|IMG) 		匹配img或IMG,非保留分组
[^>]*?style 		非>(img标签结束符)字符的非贪婪匹配
style\\s*=\\s* 		匹配img标签中的style,等号前后可能有空格
['\"] 				一个单引号或双引号
[^'\"] 				非单引号或双引号
((?!style|>).)* 	任意个非style和>的字符
密码至少8位,且同时包含英文、数字和特殊字符
// 至少8位、包含大小写字母、数字
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\[\]·~!@#¥%……&*()——\-+={}|《》?:“”【】、;‘',。、]).{8,}$
是否包含jsessionid=[32位id]
(?=.*;jsessionid\\=[0-9a-zA-Z]{32}).*
匹配逗号中的字符串
// 如123,456,789
(^|.*,)123($|,.*)
// 另一种思路
(‘,’ + dataStr + ',').indexOf(',' + '123', ',') >= 0
判断 ip 规则是否包含某 ip

如 192.168.3.%,192.168.1.1 是否包含 192.168.3.106

	/**
	 * 校验ip
	 * 支持通配符,如192.168.3.%,192.168.1.1
	 * @param rule
	 * @param ip
	 * @return
	 */
	public static boolean containsIp(String rule, String ip) {
		return Pattern.matches("("
				// 删除两端空格
				+ rule.replaceAll("(^[\\s,]+|[\\s,]+$)", "")
				// 删除相邻的,
				.replaceAll("[\\s,]+", ",")
				// 将,替换为|
				.replace(",", "|").replace(".", "\\.")
				// 将%替换为.*
				.replace("%", ".*") + ")"
				, ip);
	}

将 192.168.3.%,192.168.1.1 转换为正则表达式 (192\.168\.3\..*,|192\.168\.1\.1)去匹配 ip

js

用//包含
/\d+/.test('234')
new RegExp('\d+', 'g')
获取分组内容(必须使用参数ig
var r = /(?<=disabled\=).*?(?=;)/ig;
var result;
while(result = r.exec(curProcessFlag)) {
    var vs = result[0]
}
替换(参数 g 表示全部匹配,不使用参数 g 只替换第一个)
'aa11bb22cc'.replace(/aa\d+bb/g, '--')

java

Pattern (Java Platform SE 8 ) (oracle.com)

忽略大小写
Pattern p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
多行模式
Pattern wp = Pattern.compile("'.*?'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

xxx.replaceAll("(?s).*size:\\s(\\d+),.*", "$1")
匹配(会移动matcher指针!!!)
Pattern pattern = Pattern.compile("(\\d+)");
Matcher matcher = pattern.matcher("12266dfd3306");
System.out.println(matcher.matches());
获取分组内容
Pattern pattern = Pattern.compile("(\\d+)");
Matcher matcher = pattern.matcher("12266dfd3306");
while (matcher.find()) {
System.out.println(matcher.group(1));
}

java分组 group@
0 表示完全匹配的结果
1 第一个分组
2 第二个分组
...
替换
'aa11bb22cc'.replaceAll("aa\d+bb", "--")
Pattern wp = Pattern.compile("'.*?'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); 
Matcher m = wp.matcher(teststr);
String result = m.replaceAll("");

java Pattern.matches() 与 js //.test() 的区别

Pattern.matches() 完全匹配
    "x+"  "^x+$"
//.test() 部分匹配,即只要包含都回返回true
    'x+'  '.*x+.*'

java 正则表达式构造总结

Summary of regular-expression constructs

Construct Matches
Characters
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
\x{h...h} The character with hexadecimal value 0xh...h (Character.MIN_CODE_POINT <= 0xh...h <= Character.MAX_CODE_POINT)
\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
Character classes
[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)
Predefined character classes
. Any character (may or may not match line terminators)
\d A digit: [0-9]
\D A non-digit: [^0-9]
\h A horizontal whitespace character: [ \t\xA0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000]
\H A non-horizontal whitespace character: [^\h]
\s A whitespace character: [ \t\n\x0B\f\r]
\S A non-whitespace character: [^\s]
\v A vertical whitespace character: [\n\x0B\f\r\x85\u2028\u2029]
\V A non-vertical whitespace character: [^\v]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]
POSIX character classes (US-ASCII only)
\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]
java.lang.Character classes (simple java character type)
\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()
Classes for Unicode scripts, blocks, categories and binary properties
\p{IsLatin} A Latin script character (script)
\p{InGreek} A character in the Greek block (block)
\p{Lu} An uppercase letter (category)
\p{IsAlphabetic} An alphabetic character (binary property)
\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)
Boundary matchers
^ 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
Linebreak matcher
\R Any Unicode linebreak sequence, is equivalent to `\u000D\u000A
Greedy quantifiers
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
Reluctant quantifiers
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
Possessive quantifiers
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
Logical operators
XY X followed by Y
X` `Y
(X) X, as a capturing group
Back references
\n Whatever the nth capturing group matched
\k<name> Whatever the named-capturing group "name" matched
Quotation
\ Nothing, but quotes the following character
\Q Nothing, but quotes all characters until \E
\E Nothing, but ends quoting started by \Q
Special constructs (named-capturing and non-capturing)
(?<name>X) X, as a named-capturing group
(?:X) X, as a non-capturing group
(?idmsuxU-idmsuxU) Nothing, but turns match flags i d m s u x U on - off
(?idmsux-idmsux:X) X, as a non-capturing group with the given flags i d m s u x 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

Backslashes, escapes, and quoting

The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and \{ matches a left brace.

It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.

Backslashes within string literals in Java source code are interpreted as required by The Java™ Language Specification as either Unicode escapes (section 3.3) or other character escapes (section 3.10.6) It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.

Character Classes

Character classes may appear within other character classes, and may be composed by the union operator (implicit) and the intersection operator (&&). The union operator denotes a class that contains every character that is in at least one of its operand classes. The intersection operator denotes a class that contains every character that is in both of its operand classes.

The precedence of character-class operators is as follows, from highest to lowest:

1 Literal escape \x
2 Grouping [...]
3 Range a-z
4 Union [a-e][i-u]
5 Intersection [a-z&&[aeiou]]

Note that a different set of metacharacters are in effect inside a character class than outside a character class. For instance, the regular expression . loses its special meaning inside a character class, while the expression - becomes a range forming metacharacter.

Line terminators

A line terminator is a one- or two-character sequence that marks the end of a line of the input character sequence. The following are recognized as line terminators:

  • A newline (line feed) character ('\n'),
  • A carriage-return character followed immediately by a newline character ("\r\n"),
  • A standalone carriage-return character ('\r'),
  • A next-line character ('\u0085'),
  • A line-separator character ('\u2028'), or
  • A paragraph-separator character ('\u2029).

If UNIX_LINES mode is activated, then the only line terminators recognized are newline characters.

The regular expression . matches any character except a line terminator unless the DOTALL flag is specified.

By default, the regular expressions ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence. If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input. When in MULTILINE mode $ matches just before a line terminator or the end of the input sequence.

Groups and capturing

Group number

Capturing groups are numbered by counting their opening parentheses from left to right. In the expression ((A)(B(C))), for example, there are four such groups:

1 ((A)(B(C)))
2 (A)
3 (B(C))
4 (C)

Group zero always stands for the entire expression.

Capturing groups are so named because, during a match, each subsequence of the input sequence that matches such a group is saved. The captured subsequence may be used later in the expression, via a back reference, and may also be retrieved from the matcher once the match operation is complete.

Group name

A capturing group can also be assigned a "name", a named-capturing group, and then be back-referenced later by the "name". Group names are composed of the following characters. The first character must be a letter.

  • The uppercase letters 'A' through 'Z' ('\u0041' through '\u005a'),
  • The lowercase letters 'a' through 'z' ('\u0061' through '\u007a'),
  • The digits '0' through '9' ('\u0030' through '\u0039'),

A named-capturing group is still numbered as described in Group number.

The captured input associated with a group is always the subsequence that the group most recently matched. If a group is evaluated a second time because of quantification then its previously-captured value, if any, will be retained if the second evaluation fails. Matching the string "aba" against the expression (a(b)?)+, for example, leaves group two set to "b". All captured input is discarded at the beginning of each match.

Groups beginning with (? are either pure, non-capturing groups that do not capture text and do not count towards the group total, or named-capturing group.

Pattern (Java Platform SE 8 ) (oracle.com)