简体   繁体   English

Java正则表达式匹配一个反斜杠

[英]Java-Regular Expression to match one backslah

Hi I am trying to do a regular expresion that match one and only one time "\" so I can detect one directory level this example not work I don't know very regular expresion in Java.您好,我正在尝试做一个匹配一次且仅匹配一次“\”的正则表达式,这样我就可以检测到一个目录级别这个例子不起作用我不知道 Java 中的正则表达式。

    String  input="C:\\andres\\an";
//    String  input="C:\\andres";
    Pattern p = Pattern.compile("\\\\{1}");
    Matcher m = p.matcher(input);
    if (m.find()) {
        System.out.println("La cadena SI contiene un caracter \\");
        System.out.println(input);
    }else {
        System.out.println("La cadena no contiene un caracter \\");
        System.out.println(input);
    }
}

You can do this easily using a negated character class regex:您可以使用否定的字符类正则表达式轻松地做到这一点:

^[^\\]*\\[^\\]*$ 

In Java regex string would be:在 Java 中正则表达式字符串将是:

final String regex = "^[^\\\\]*\\\\[^\\\\]*$";

RegEx Demo正则表达式演示

RegEx Details:正则表达式详细信息:

  • ^ : Start ^ : 开始
  • [^\\]* : Match 0 more of any characters that are not \ [^\\]* :再匹配 0 个不是\的字符
  • \\ : Match a single \ \\ :匹配单个\
  • [^\\]* : Match 0 more of any characters that are not \ [^\\]* :再匹配 0 个不是\的字符
  • $ : End $ : 结束

PS: If you're using this regex in .matches() method then anchors ^ and $ are not needed and you can just use: PS:如果您在.matches()方法中使用此正则表达式,则不需要锚点^$ ,您可以使用:

final String regex = "[^\\\\]*\\\\[^\\\\]*";

I would use this pattern:我会使用这种模式:

^(?!.*\\.*\\).*\\.*$

This regex asserts that two (or more) backslashes do not appear.此正则表达式断言不会出现两个(或更多)反斜杠。 Then, it goes on to match a single backslash.然后,它继续匹配单个反斜杠。 In Java code:在 Java 代码中:

String input = "C:\\andres";
if (input.matches("(?!.*\\\\.*\\\\).*\\\\.*")) {
    System.out.println("MATCH");
}

But, String#split might offer an even easier way of doing this:但是, String#split可能会提供一种更简单的方法:

String input = "C:\\andres";
if (input.split("\\\\").length == 2) {
    System.out.println("MATCH");
}

A matching path, with only one backslash, when split on backslash should have exactly two resulting terms.一个匹配路径,只有一个反斜杠,当在反斜杠上分割时,应该恰好有两个结果项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM