1.是否包含字符
Java
Pattern.matches(正则表达式, 字符串)
import java.util.regex.*;
class RegexExample1{
public static void main(String args[]){
String content = "I am noob from runoob.com.";
String pattern = ".*runoob.*";
boolean isMatch = Pattern.matches(pattern, content);
System.out.println("字符串中是否包含了 'runoob' 子字符串? " + isMatch);
}
}
// 输出结果:字符串中是否包含了 'runoob' 子字符串? true
JS
正则表达式.test(字符串)
/e/.test("The best things in life are free!");
// 输出结果:true
2.替换
Java
Pattern.compile(正则表达式).matcher(原字符串).replaceAll(替换字符串)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
private static String REGEX = "dog";
private static String INPUT = "The dog says meow. All dogs say meow.";
private static String REPLACE = "cat";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
// 输出结果:The cat says meow. All cats say meow.
JS
原字符串.replace(正则表达式,替换字符串)
"wzm".replace(/wzm/i,"wangzemin");
// 输出结果:wangzemin
网友评论