java学习笔记之正则表达式

时间:2023-03-09 01:08:57
java学习笔记之正则表达式

一般来说,正则表达式就是以某种方式来描述字符串,因此你可与说:"如果一个字符串符合有这些东西,那么它就是我正在找的东西。

1、要找一个数字,如果它可能有一个负号在最前面(可能没有,没有也是匹配的),那么久这样写:-?

2、要描述一个整数,你可以说它有一个或多个阿拉伯数字。

此时可以用\d表示一位数字。

在java中,\\表示"我要插入一个正则表达式的反斜线,所以其后的字符具有特殊的意义。"

例如,表示一位数字,正则表达式应该是\\d.表达普通的反斜线,则是\\\\/、、。

若是换行和制表之类的东西只需使用单反斜线:\n\t。

要表示"一个或多个之前的表达式",应该使用+。所以,如果要表示可能有一个负号,后面跟着一位或多位数字,可以这样:-?\\d+

看一段例子:

           System.out.println("-5678".matches("-?\\d+"));
System.out.println("-5678-".matches("-?\\d+"));
System.out.println("-5678-".matches("-?\\d+-?"));
System.out.println("-5678-".matches("(-?|\\+)\\d+-?"));
System.out.println("-+5678-".matches("(-?|\\+)\\d+-?"));
System.out.println("+5678-".matches("(-?|\\+)\\d+-?"));
String knights="Then, when you have found the shrubbery,you must "
+ "cut down the mightiest tree in the forest..."
+ "with...a herring!";
System.out.println(Arrays.toString(knights.split(" ")));//split()方法能将字符串从正则表达式匹配的地方切开。
System.out.println(Arrays.toString(knights.split("\\W+")));
System.out.println(Arrays.toString(knights.split(",")));
System.out.println(Arrays.toString(knights.split("n\\W+"))); /*
输出:
true
false
true
true
false
true
[Then,, when, you, have, found, the, shrubbery,you, must, cut, down, the, mightiest, tree, in, the, forest...with...a, herring!]
[Then, when, you, have, found, the, shrubbery, you, must, cut, down, the, mightiest, tree, in, the, forest, with, a, herring]
[Then, when you have found the shrubbery, you must cut down the mightiest tree in the forest...with...a herring!]
[The, whe, you have found the shrubbery,you must cut dow, the mightiest tree i, the forest...with...a herring!] */