Frank
Frank

Reputation: 7585

Java regex match with slash

I want to match words "N/A" or "None".

So I used

public static final String NA = "/^(n\\/a|none)$/i";

It doesn't work in java. Can you help?

Upvotes: 1

Views: 2314

Answers (3)

mrres1
mrres1

Reputation: 1155

Checks for a forward or backward slash

The regular expression would be written as (?i)n[/|\\]a|none

To use this in a String you'll need to escape the backward slash:

String pattern = "(?i)n[/|\\\\]a|none";

String[] array = 
    {
        "N/a",
        "n\\a",
        "NonE",
        "na"
    };

for(String item : array)
{
    System.out.println("\"" + item + "\" = " + item.matches(pattern));
}

Console:

"N/a" = true
"n\a" = true
"NonE" = true
"na" = false

Upvotes: 0

falsetru
falsetru

Reputation: 369444

Java does not use / as a regular expression literal. (No need to escape / itself). If you want to ignore case, you can use a modifier (?i) inside the regular expression:

String NA = "^(?i)(n/a|none)$";

Or, you can use Pattern.CASE_INSENSITIVE when you compile the pattern.

String NA = "^(n/a|none)$";
Pattern p = Pattern.compile(NA, Pattern.CASE_INSENSITIVE);

Upvotes: 2

Andie2302
Andie2302

Reputation: 4897

To match "N/A" or "None" in Java use:

(?i)\b(?:n/a|none)\b

As escaped java String:

"(?i)\\b(?:n/a|none)\\b"

Upvotes: 0

Related Questions