import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegexTester
{
final static String regex = "^[\\/\\.].*$";
final static String[] stringsToTest = { ".file",
"./file",
"/file",
"/.file",
".",
"./",
"/some/path",
"/some-path/.some-file",
"/path/path/.file",
"/path/.file",
"/asfas/.d",
"/path/.file" };
final static Pattern pattern = Pattern.compile(regex);
public static void main(String[] args)
{
for (String text : stringsToTest) {
testRegex(text);
}
}
public static void testRegex(String testString)
{
Matcher matcher = pattern.matcher(testString);
while (matcher.find())
{
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++)
{
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
输出为:
javac RegexTester.java && java RegexTester
Full match: .file
Full match: ./file
Full match: /file
Full match: /.file
Full match: .
Full match: ./
Full match: /some/path
Full match: /some-path/.some-file
Full match: /path/path/.file
Full match: /path/.file
Full match: /asfas/.d
Full match: /path/.file
# 1 楼答案
^[\/\.].*$
将检查字符串是否以开头或/以下是java代码:
输出为:
Run this java code in rextester.com
# 2 楼答案
^\.
或^[.]
将匹配前导点。而且^[/][.]
将匹配起始/.
# 3 楼答案
对于您发布的问题:不需要正则表达式
如果你想要正则表达式,因为它很酷,就用这个
(基于您的评论)如果您想检查路径中的最后一段之类的内容
如果实际匹配的文件名是Path
# 4 楼答案
那么:
这与可选的斜杠和字符串开头的点匹配
根据评论,我猜你想匹配:
这将匹配一个可选的斜杠,并在字符串末尾加上一个点,然后再加上一个或多个非斜杠或点的字符