一个小问题

ZiSheng 2009-06-28 12:18:09
正则(.)*和[.]*
的区别
...全文
35 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
默然说话 2009-06-28
  • 打赏
  • 举报
回复
小括号表示一个组,它可以是一个字符,也可以是多个字符,如(a|b|c|d)意思就是a或b或c或d任意一个,(abc|like|love)则是表示abc或like或love任意一个。

中括号表示只表示一个字符的可选范围,如[a-z]表示这个字符可以是所有小写字符。
micsolaris 2009-06-28
  • 打赏
  • 举报
回复
放到metacharacter中的和在外部很多是有区别的。比如.在外部的时候是匹配任意字符,但是在[]里却是匹配一个点
qqqwwwqw 2009-06-28
  • 打赏
  • 举报
回复
前面匹配,后面不匹配吧
icesnows 2009-06-28
  • 打赏
  • 举报
回复
学习下,正则表达式还不懂
ZiSheng 2009-06-28
  • 打赏
  • 举报
回复
现在应该清楚了,元字符在[]和()中的意思是不同的。
ZiSheng 2009-06-28
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 micsolaris 的回复:]
放到metacharacter中的和在外部很多是有区别的。比如.在外部的时候是匹配任意字符,但是在[]里却是匹配一个点
[/Quote]
应该是这个意思,元字符.放在[]中是匹配一个.放在()中则是匹配任意字符。搞的我迷惑。
找了个例子:

import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTestHarness {

public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("No console.");
System.exit(1);
}

while (true) {
Pattern pattern = Pattern.compile(console.readLine("%nEnter your regex: "));
Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: "));
boolean found = false;
while (matcher.find()) {
console.format("I found the text \"%s\" starting at index %d " +
"and ending at index %d.%n",
matcher.group(), matcher.start(), matcher.end());
found = true;
}
if (!found) {
console.format("No match found.%n");
}
}
}
}

out:

Enter your regex: (.)*
Enter input string to search: ddd
I found the text "ddd" starting at index 0 and ending at index 3.
I found the text "" starting at index 3 and ending at index 3.

Enter your regex: [.]*
Enter input string to search: ddd
I found the text "" starting at index 0 and ending at index 0.
I found the text "" starting at index 1 and ending at index 1.
I found the text "" starting at index 2 and ending at index 2.
I found the text "" starting at index 3 and ending at index 3.
冥王之锤 2009-06-28
  • 打赏
  • 举报
回复
正则(.)*匹配任意多个字符,和[.]* 匹配多个.

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧