Java正则表达式
Java,JavaScript与Shell中使用的正则表达式的差异以及相互转换
- Java的字符串中,
\表示转义字符,因此要保留在正则表达式中的转移字符\,需要使用\\
- 使用
Pattern类的compile方法创建一个Pattern对象,matcher方法来获取一个Matcher对象
1 2 3 4 5
| String message = "somebody@demo.com";
Pattern pattern = Pattern.compile("^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$"); boolean isMatch = pattern.matcher(message).matches();
|
1 2 3
| String message = "somebody@demo.com"; String regex = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$"; boolean isMatch = Pattern.matches(regex, message);
|
1 2 3 4
| String message = "somebody@demo.com"; String regex = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$"; boolean isMatch = message.matches(regex);
|
Shell中不需要对正则表达式做额外处理,直接使用
1 2 3 4
| REGEX="^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$" FILE="/opt/somefile"
grep $REGEX $FILE
|
- JavaScript中也不需要对正则表达式做额外处理,直接使用
正则表达式相关字符串操作
- 替换,参考
Matcher的replaceFirst()和replaceAll()方法
- 追加替换,参考
Matcher的appendReplacement和appendTail()方法
常用正则表达式
1
| ^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$
|
1
| ^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$
|