首先正则表达式在处理字符串问题时,真的非常强大。
正则可以帮助我们处理字符串的: 匹配, 选择, 编辑, 验证等问题。
正则中"\\"表示插入一个"\"
这里仅是记录String 与 正则的结合:
1:验证:
import java.util.Arrays;import java.util.Scanner;public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner cin = new Scanner(System.in); System.out.println("-1234".matches("-?\\d+")); //可能以-开头以数字结尾的 System.out.println("5678".matches("-?\\d+")); System.out.println("+1234".matches("-?\\d+")); System.out.println("+2344".matches("(-|\\+)?\\d+"));//可能以-或者+开头以数字结尾的 }} 输出:
true
truefalsetrue
2:分割字符串:
结合split进行分割:
import java.util.Arrays;import java.util.Scanner;public class Main { public static String s = "I am a good student... haha"; public static void main(String[] args) { //以空格进行分割,返回一个list System.out.println( Arrays.asList(s.split(" ")) ); //以非字符进行分割 W表示一个 W+表示后边跟任意个 System.out.println( Arrays.asList(s.split("\\W+"))); //以以g开头后边跟字符的进行分割 System.out.println( Arrays.asList(s.split("g\\w+"))); }}输出:[I, , , am, a, good, student..., haha][I, am, a, good, student, haha][I am a , student... haha]
4:替换:
import java.util.Arrays;import java.util.Scanner;public class Main { public static String s = "I am a good student... haha good"; public static void main(String[] args) { System.out.println(s.replaceFirst("g\\w+", "very good")); System.out.println(s.replaceAll("g\\w+", "very good")); }}输出:I am a very good student... haha goodI am a very good student... haha very good
然后发现之前自己在oj上的一道简单的题目Java几行代码就解决了:
SDUT 2192
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner cin = new Scanner(System.in); int n = cin.nextInt(); String s = null; for (int i = 0; i < n; ++i) { s = cin.next(); System.out.println(s.replaceAll("cRazY", "CrAZy").replaceAll("CraZy", "cRAzY")); } } }