如何在字符串中找到转义符\?

时间:2018-08-04 13:40:07

标签: design-patterns escaping character expression

请考虑以下代码:

public static void main(String... args) {

        int count = 0;
        Pattern pattern = Pattern.compile("X");
        Matcher matcher = pattern.matcher("5\\yeyyyyyyy");
        while (matcher.find()) {
            count++;
            System.out.println(matcher.start()+"..."+matcher.group());
        }
        System.out.println("The total number of occurrences "+count);

    }

1)如果我在上面的程序中写了x = 5,那么我得到以下输出:

0...5
The total number of occurrences 1

所以我得到的信息是5在0索引处,并且在给定的字符串中只有一次。

2)相似我们知道//位于1索引处,并且在给定的字符串中只有一次。如何获得此输出?

我正在尝试写

x=// 

我遇到编译时错误。

我希望我让你们了解我的观点。 谢谢

1 个答案:

答案 0 :(得分:1)

您必须使用双引号。因此,在您的情况下,该名称将为“ \\\\”。

Pattern pattern = Pattern.compile("\\\\");

如果需要转发斜杠,则:“ \\ /”