13.6 正则表达式

前端之家收集整理的这篇文章主要介绍了13.6 正则表达式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
?表示有或没有,+表示一个或多个,()用来分组表达式,\\为在正则中插入转义符,但插入制表符只需要写\t等,无需双反斜杠,如果要插入反斜杠字符,要写四个反斜杠\\\\(转义符的转义符?),需要注意的是,写入+符号的时候,因为其在正则中是特殊字符,需要转义\\+
package com.cnsuning.src;
import java.util.Formatter;
public class Main {
	private Formatter f = null;
	public Main() {
		// TODO Auto-generated constructor stub
		this.f = new Formatter(System.out);
	}
	public static void main(String[] args) {
		System.out.println("-28".matches("-?\\d+"));
		System.out.println("-28.6".matches("-?\\d+"));
		System.out.println("-28.6".matches("-?\\d+.?\\d+"));
		System.out.println("28".matches("-?\\d+"));
		System.out.println("+28".matches("-?\\d+"));
		System.out.println("+28".matches("(-|\\+)?\\d+"));
	}
}

truefalsetruetruefalsetrueString
还有一个与正则相关的函数split,用来利用正则表达式分割字符串
package com.cnsuning.src;
import java.util.Arrays;
import java.util.Formatter;
public class Main {
	private Formatter f = null;
	public Main() {
		// TODO Auto-generated constructor stub
		this.f = new Formatter(System.out);
	}
	public static void main(String[] args) {
		split("This is a test case."," ");
		split("Now,we input second statement.","\\W+");
		split("Now,"n\\W+");
	}
	public static void split(String source,String exp){
		String[] array = source.split(exp);
		System.out.println(Arrays.toString(array));
	}
}

String还带有根据正则表达式来替换的函数

public static void main(String[] args) {
		System.out.println("This is a test case.".replaceAll(" \\w+","moon"));
		System.out.println("This is a test case.".replaceFirst(" \\w+","moon"));
		System.out.println("This is a test case.".replace(" \\w+","moon"));
	}

Thismoonmoonmoonmoon.
Thismoon a test case.
This is a test case.
原文链接:https://www.f2er.com/regex/361498.html

猜你在找的正则表达式相关文章