问题描述:

I am having a string which has a delimiter like "|"

e.g. "South NY, US | South-East NY, US| North NY, US"

note: the space around the pipe on either side may or may not appear.

I have been trying to use .contains() to match a given string, but it also match the case like "East NY, US"

I have got a small function (in java) to match a search string, but it is inefficient.

boolean fullmatch (String search, String text) {

String[] split = text.split ("\\|");

for (int i = 0; i < split.length; i++) {

if (split[i].trim().equals (search)) {

return true;

}

}

return false;

}

What would be the equivalent regex for this? Thanks you

additional: What would be the equivalent regex in SQL too? (trying not to pull out large amount of data for comparison in Java)

网友答案:

I doubt that your method is too inefficient, or that you can make it much more efficient; but for cleaner and simpler code (which also will perform at least somewhat better), you can write:

boolean fullmatch (String search, String text) {
    return Pattern.compile(
        "(?:^|\\|)\\s*" + Pattern.quote(search) + "\\s*(?:\\||$)")
        .matcher(text).find();
}

For example, if your search is "South-East NY, US", then the above will return true if text contains a substring matching (?:^|\|)\s*South-East NY, US\s*(?:\||$) (start-of-string-or-pipe, plus optional whitespace, plus the search-string, plus optional whitespace, plus pipe-or-end-of-string).

网友答案:

Try this:

boolean fullmatch (String search, String text) {
    return text.matches(".*(^|\\|)\\s*" + search + "\\s*(\\||$).*");
}
相关阅读:
Top