正则表达式中的点行为 [英] Dot behavior in regex patterns

查看:148
本文介绍了正则表达式中的点行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Pattern p2 = Pattern.compile(".*");
Matcher m2 = p2.matcher("true");
System.out.println(m2.matches() + " [" + m2.group() + "]");

当我使用上面的代码时,它是可以的。但是当我使用这个regexpr [。] * 时,我不明白发生了什么。它打印 false

When I use the code above it is all right. But I don't understand what is going on when I use this regexpr [.]*. It prints false.

如何将点作为特定符号?或者如何使用没有\\\
和\ r的任何字符制作一类符号?

How to make a dot as a specific symbol? Or how to make a class of symbols with any characters without \n and \r?

推荐答案


<但是,当我使用这个regexpr [。] *时,我不明白发生了什么。它说我是假的。

But I don't understand what is going on when I use this regexpr [.]*. It says me false.

因为在字符类,点失去其特殊含义,并将匹配一个普通的旧点(字符)。

Because inside a character class, the dot loses its special meaning and will match a plain old dot (the . character).

在字符类之外,点是与任何字符匹配的元字符,不包括换行符(除非您使用 Pattern.DOTALL 修饰符,当然)。

Outside of a character class the dot is a metacharacter that matches any character, excluding newlines (unless you use the Pattern.DOTALL modifier, of course).


或者如何使用任何没有\\\
和\r的字符创建符号类。

Or how to make a class of symbols with any characters without \n and \r.

使用否定字符类:

 Pattern p2 = Pattern.compile("[^\\r\n]*");

[^ \\\\ n] 表示匹配任何 \ r 或 \ n

[^\r\n] means "match anything that's not a \r or a \n.

这篇关于正则表达式中的点行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆