廖雪峰Java9正则表达式-2正则表达式进阶-6搜索和替换

java

1.使用正则表达式分割字符串:

        String[] string.split(String regex);

"a b c".split("\\s");->[a, b, c]

"a b c".split("\\s");->[a, b, , , , c]

"a b c".split("\\s+");->[a, b, c]

"a,b:;c".split("[\\,\\:\\;\\s]+");->[a, b, c]

    public static void main(String[] args){

String tags = "java php python";

String[] arr = tags.split("\\s");

System.out.println(Arrays.toString(arr));

}

```#java

public class SplitString {

public static void main(String[] args){

String tags = "java php python";

String[] arr = tags.split("\\s+");

System.out.println(Arrays.toString(arr));

}

}

```

```#java

public class SplitString {

public static void main(String[] args){

String tags = "java, php;: python";

String[] arr = tags.split("[\\,\\;\\:\\s]+");

System.out.println(Arrays.toString(arr));

}

}

```

2.使用正则表达式查找字符串

package com.testList;

import java.util.Arrays;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class SearchString {

public static void main(String[] args){

String s = "The quick brown fox jumps over the lazy dog.";

//区分大小写

Pattern p1 = Pattern.compile("the");

Matcher m1 = p1.matcher(s);

while(m1.find()){

String sub = s.substring(m1.start(),m1.end());

System.out.print(sub+",start="+m1.start()+" end="+m1.end()+"\t");

}

System.out.println();

//不区分大小写

Pattern p2 = Pattern.compile("the",Pattern.CASE_INSENSITIVE);

Matcher m2 = p2.matcher(s);

while(m2.find()){

String sub = s.substring(m2.start(),m2.end());

System.out.print(sub+",start="+m2.start()+" end="+m2.end()+"\t");

}

System.out.println();

//匹配每个单词

Pattern p3 = Pattern.compile("\\w+",Pattern.CASE_INSENSITIVE);

Matcher m3 = p3.matcher(s);

while(m3.find()){

String sub = s.substring(m3.start(),m3.end());

System.out.print(sub+",start="+m3.start()+" end="+m3.end()+"\t");

}

System.out.println();

//匹配带有o的单词

Pattern p4 = Pattern.compile("\\w*o\\w*",Pattern.CASE_INSENSITIVE);

Matcher m4 = p4.matcher(s);

while(m4.find()){

String sub = s.substring(m4.start(),m4.end());

System.out.print(sub+",start="+m4.start()+" end="+m4.end()+"\t");

}

}

}

3.使用正则表达式替换字符串

public class SplitString {

public static void main(String[] args){

String s = "The quick brown fox jumps over the lazy dog.";

//区分大小写

String r = s.replaceAll("\\s+"," ");//参数依次为正则表达式,用于替换的字符

System.out.println(r);

String r2 = s.replaceAll("(\\w+)","<b>$1</b>");//$1方向引用,指向前面捕获的单词

System.out.println(r2);

}

}

4.总结

使用正则表达式可以:

  • 分割字符串:String .split()
  • 搜索字串:Matcher.find()
  • 替换字符串:String.replaceAll()

以上是 廖雪峰Java9正则表达式-2正则表达式进阶-6搜索和替换 的全部内容, 来源链接: utcz.com/z/391267.html

回到顶部