问题描述
我有逗号分隔的正则表达式列表:
I have comma separated list of regular expressions:
.{8},[0-9],[^0-9A-Za-z ],[A-Z],[a-z]
我对逗号做了一个拆分.现在我正在尝试将此正则表达式与生成的密码进行匹配.问题是Pattern.compile
不喜欢没有转义的方括号.
I have done a split on the comma. Now I'm trying to match this regex against a generated password. The problem is that Pattern.compile
does not like square brackets that is not escaped.
请给我一个简单的函数,它接受一个像这样的字符串:[0-9]
并返回转义的字符串 \[0-9\]
.
Can some please give me a simple function that takes a string like so: [0-9]
and returns the escaped string \[0-9\]
.
推荐答案
您可以使用 Pattern.quote(String)
.
You can use Pattern.quote(String)
.
来自文档:
public static String quote (String s)
返回指定String
的文字模式String
.
此方法生成一个字符串,该字符串可用于创建一个模式,该模式将匹配字符串 s,就好像它是一个文字模式一样.
This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.
输入序列中的元字符或转义序列将没有特殊含义.
Metacharacters or escape sequences in the input sequence will be given no special meaning.
这篇关于如何为模式编译转义方括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!