匹配任意字符(包括中英文及任意标点)的正则表达式
Regex : \\w*|\\W*|[\\u4e00-\\u9fa5]
这个表达式匹配一个任意中英文字符.
- 其中:
\w
: A word character: [a-zA-Z_0-9](匹配一个单词字符); - 其中:
\W
: A non-word character: [^\w](匹配一个非单词字符); - 其中:
[\\u4e00-\\u9fa5]
: 匹配一个中文字符;
Ref:http://saltdstar.iteye.com/blog/1041690
Ref:http://www.jb51.net/article/19713.htm
Ref:http://www.jb51.net/article/64301.htm
测试用例:
package cn.mike.march;
public class MatchesAllCharactersIncludeChinese {
public static void main(String[] args) {
String singleWordRegex = "\\w*|\\W*|[\\u4e00-\\u9fa5]";
String chineseCharacter = "犇";
System.out.println("1_: " + chineseCharacter.matches(singleWordRegex));
String multipleWordsRegex = "(\\w*|\\W*|[\\u4e00-\\u9fa5]*)*";
String exampleCharacters = "我的天as牛牪犇df134牛牪犇wsdf64?><?>|_!@@!:;…#$%%^&*(啊.。?";
System.out.println("2_: " + exampleCharacters.matches(multipleWordsRegex));
String regex = "^[A-Z]{1}(\\w*|\\W*|[\\u4e00-\\u9fa5]*)*[。]{1}$";
String exampleChars3 = "B我的天asdf13464?><?>|_!@@#$%%^&*(啊。";
System.out.println("3_: " + exampleChars3.matches(regex));
}
}
/** Output:
1_: true
2_: true
3_: true
*/
附录:
- 匹配中文字符的正则表达式: [\u4e00-\u9fa5]
- 匹配双字节字符(包括汉字在内):[^\x00-\xff]
- 在文本文件里, 这个表达式可以匹配所有的英文 :
/[ -~]/
- 这个表达式可以匹配所有的非英文(比如中文) :
/[^ -~]/
注意:表达式中间有一个空格;
正则表达式工具:
- JavaScript正则表达式在线测试工具:http://tools.jb51.net/regex/javascript
- 正则表达式在线生成工具 : http://tools.jb51.net/regex/create_reg
by Mike Sun @ 20170330