java 代码
// Java中 获取指定字符串在另一个字符串中出现的次数 //方法一、//不区分大小写 String str = "Hello,my name is Ben.Please visit my website at http://www.forta.com/."; String regex = "My"; Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE); int count = 0; Matcher match = pattern.matcher(str); while (match.find()) { count++; } System.out.println(count); //方法一、//区分大小写 String regex1 = "my"; Pattern pattern1 = Pattern.compile(regex1,Pattern.CASE_INSENSITIVE);//不区分大小写 int count1 = 0; Matcher match1 = pattern1.matcher(str); while (match1.find()) { count1++; } System.out.println(count1); //方法二、 String reg = "my"; int count2 = 0; int index1 = 0; //indexOf方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回 -1 while ((index1 = str.indexOf(reg, index1)) != -1) { index1 = index1 + reg.length(); count2++; } System.out.println(count2); 2 2 2
替换不区分大小写
String input = "I like Java,jAva is very easy and jaVa is so popular."; String replacement="ccc"; System.out.println(input); System.out.println(input.replaceAll("java", replacement)); System.out.println(input.replaceAll("(?i)java", replacement)); I like Java,jAva is very easy and jaVa is so popular. I like Java,jAva is very easy and jaVa is so popular. I like ccc,ccc is very easy and ccc is so popular.
javascript 代码
ffunction myFunction(){ //方法一、 通过分割获取长度原理 var str = "Hello,my name is Ben.Please visit my website at http://www.forta.com/."; var regex = "my"; var n = (str.split(regex)).length-1; alert(n); //方法二、通过正则实现 //eval(string) 函数可计算某个字符串,并执行其中的的 JavaScript 代码。 var reg=eval("/My/ig");//g代表全局查找,i代表不区分字母大小写 var count = str.match(reg).length; alert(count); } 都弹出 2