正则表达式

时间:2019-01-09 13:17:39

标签: java regex

如何为接受字符串的正则表达式

  1. 仅在双引号后面加上反斜杠时才使用双引号
  2. 如果反斜杠的数量为奇数,则最后一个反斜杠应包含特殊字符或任何文字或字母

示例:- 正则表达式不应该接受以下内容

"""
"\"
"\\\"

正则表达式应接受以下内容

"\""
"\r"
"\ "  here the single backslash is having space after it so it is should be accepted.
"\\"
"\\\cloud"
"\\\ "
"clo$d"
"cloud space" 

1 个答案:

答案 0 :(得分:0)

在Java中看起来确实很丑陋,但在Java和REGEX中转义了反斜杠:

static String REGEX = "([^\"\\\\]|\\\\[^\\\\]+|\\\\\\\\)+";

public static void main(String[] args) {

    test("\"");
    test("\\");
    test("\\\\\\");
    System.out.println();
    test("\\\"");
    test("\\r");
    test("\\ ");
    test("\\\\\\cloud");
    test("\\\\\\ ");
    test("clo$d");
    test("cloud space");
}

public static void test(String s) {
    System.out.println(s + ": " + REGEX + " " + Pattern.matches(REGEX, s));
}