正则表达式匹配JAVA中的斜杠 [英] Regex to match both slash in JAVA

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

问题描述

我想匹配正斜杠 / 或反斜杠 \ 特别是字符串,例如:

1. 您好/您好/再见/

2. Hi \Hello \ Bye \

3. Hi\Hello / Bye \

4. HiHelloBye

在给定的字符串中,只有最后一条记录不匹配,因为它不包含 / \

I want to match forward slash / or back slash \ in particular string for e.g.:
1. Hi/Hello/Bye/
2. Hi\Hello\Bye\
3. Hi\Hello/Bye\
4. HiHelloBye
In the given strings only the last record should not be matched because it does not contain either / or \.

我使用的是什么

if (strFile.matches(".*//.*"))
{
    //String Matches.
}
else
{
    //Does not match.
}

这匹配正斜杠 / 。我不知道如何为斜线写入正则表达式(对于 OR 条件)。

This matches for forward slash / only. I don't know how to write regex for both slash (for OR condition).

推荐答案

你想要匹配的字符是:

"[/\\\\]"

首先为字符串复制反斜杠然后再为正则表达式重复。

duplicating the backslash first for the string then again for the regex.

当你需要在使用反斜杠转义字符串的语言中使用反斜杠时,这可能是最糟糕的正则表达式。

This is perhaps the nastiest bit of regexes when you need to use backslashes in languages that also use the backslash for escaping strings.

Java编译器在源代码中看到字符串\\\\并实际将其转换为\ \(因为它使用 \ 作为转义字符)。

The Java compiler sees the string "\\\\" in the source code and actually turns that into "\\" (since it uses \ as an escape character).

然后正则表达式看到\\,因为它还使用 \ 作为转义字符,将它视为单个 \ 字符。

Then the regular expression sees that "\\" and, because it also uses \ as an escape character, will treat it as a single \ character.


作为刘艳点在评论中,您可以使用以下方法之一摆脱一个级别的反斜杠(正则表达式):

As Liu Yan points out in a comment, you could get rid of one level of backslashes (the regex one) by using one of the following:



".*[/\\x5c].*"
".*[/\\u005c].*"




这可能会使其更具可读性。

That might make it slightly more readable.

完成所有减少后,您指定了一个由两个斜杠组成的字符类,如果所讨论的字符与其中任何一个匹配,则返回true。

Once all that reduction is done, you have specified a character class consisting of both slashes and, if the character in question matches either of them, it returns true.

以下代码显示了这一点:

The following code shows this in action:

public class testprog {
    public static void checkString (String s) {
        boolean yes = s.matches(".*[/\\\\].*");
        System.out.println ("'" + s + "': " + yes);
    }

    public static void main (String s[]) {
        checkString ("Hi/Hello/Bye/");
        checkString ("Hi\\Hello\\Bye\\");
        checkString ("Hi\\Hello/Bye\\");
        checkString ("HiHelloBye");
    }
}

并输出:


    'Hi/Hello/Bye/': true
    'Hi\Hello\Bye\': true
    'Hi\Hello/Bye\': true
    'HiHelloBye': false

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

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