- Сопоставление строк без учета регистра в Java
- 1. Обзор
- 2. Самое Простое Решение: Строка.toLowerCase
- 3. Строка.спички С Регулярными Выражениями
- 4. String.regionMatches
- 5. Шаблон С параметром CASE_INSENSITIVE
- 6. Apache Commons StringUtils.containsIgnoreCase
- 7. Сравнение Производительности
- 8. Заключение
- Читайте ещё по теме:
- Java RegEx Case Insensitive Example
- How to make Java RegEx case insensitive?
- 1) Using Pattern class
- 2) Using (?i) modifier
- How to make partial regex case insensitive?
- About the author
Сопоставление строк без учета регистра в Java
Узнайте, как выполнить сопоставление строк без учета регистра в Java.
1. Обзор
Существует множество способов проверить, содержит ли строка подстроку . В этой статье мы будем искать подстроки внутри String , сосредоточившись на обходных путях без учета регистра для String.contains() в Java. Самое главное, мы приведем примеры того, как решить эту проблему.
2. Самое Простое Решение: Строка.toLowerCase
Самое простое решение-использовать String.toLowerCase() . В этом случае мы преобразуем обе строки в нижний регистр, а затем используем метод contains() :
assertTrue(src.toLowerCase().contains(dest.toLowerCase()));
Мы также можем использовать String.toUpperCase (), и это даст тот же результат.
3. Строка.спички С Регулярными Выражениями
Другой вариант-использовать String.matches() с регулярными выражениями:
assertTrue(src.matches("(?i).*" + dest + ".*"));
Метод matches() принимает как попытку представить регулярное выражение. (?i) включает нечувствительность к регистру и .* использует все символы, кроме разрывов строк.
4. String.regionMatches
Мы также можем использовать String.regionMatches() . Он проверяет, совпадают ли две области String , используя true для параметра IgnoreCase :
public static boolean processRegionMatches(String src, String dest) < for (int i = src.length() - dest.length(); i >= 0; i--) if (src.regionMatches(true, i, dest, 0, dest.length())) return true; return false; >
assertTrue(processRegionMatches(src, dest));
Чтобы повысить производительность, он начинает сопоставлять регион с учетом длины целевой строки . Затем он уменьшает итератор.
5. Шаблон С параметром CASE_INSENSITIVE
Класс java.util.regex.Pattern предоставляет нам способ сопоставления строк с помощью метода matcher () . В этом случае мы можем использовать метод quote() для экранирования любых специальных символов и флаг CASE_INSENSITIVE . Давайте посмотрим:
assertTrue(Pattern.compile(Pattern.quote(dest), Pattern.CASE_INSENSITIVE) .matcher(src) .find());
6. Apache Commons StringUtils.containsIgnoreCase
Наконец, мы воспользуемся классом Apache Commons StringUtils:
assertTrue(StringUtils.containsIgnoreCase(src, dest));
7. Сравнение Производительности
Как и в этой общей статье о проверке подстрок с помощью метода contains , мы использовали фреймворк с открытым исходным кодом Java Microbenchmark Harness (JMH) для сравнения производительности методов в наносекундах :
- Регулярное выражение Pattern CASE_INSENSITIVE: 399.387 нс
- Строка toLowerCase : 434.064 ns
- Apache Commons StringUtils : 496.313 ns
- Совпадения области строки : 718.842 нс
- Строка совпадает с регулярным выражением : 3964.346 ns
Как мы видим, победителем является Pattern с включенным флагом CASE_INSENSITIVE , за которым следует toLowerCase() . Мы также заметили явное улучшение производительности между Java 8 и Java 11.
8. Заключение
В этом уроке мы рассмотрели несколько различных способов проверки String на наличие подстроки, игнорируя при этом случай в Java.
Мы рассмотрели использование String.toLowerCase() и toUpperCase() , String.matches() , String.regionMatches() , Apache Commons StringUtils.containsIgnoreCase() , и Pattern.matcher().find() .
Кроме того, мы оценили производительность каждого решения и обнаружили, что использование метода compile() из java.util.regex.Pattern с флагом CASE_INSENSITIVE работает лучше всего .
Читайте ещё по теме:
Java RegEx Case Insensitive Example
Java RegEx Case Insensitive example shows how to make Java regex case insensitive. The example also shows how to make Java regular expression case insensitive using (?i) modifier as well as Pattern class.
How to make Java RegEx case insensitive?
By default Java regular expressions are case sensitive. Consider below given example.
The string against which we evaluated our expression has a “second” word 3 times, but the pattern only matched once. The reason is two “second” words have the first character in capital letters. Since the Java regular expressions are case sensitive by default they did not match with our pattern which has all the lower case letters.
There are a couple of ways using which you can make your regex case insensitive.
1) Using Pattern class
Instead of using the compile method of Pattern class with just pattern argument, you can use overloaded compile method which accepts various flags along with the pattern. For making pattern case insensitive you need to specify Pattern.CASE_INSENSITIVE flag as given below.
As you can see from the output, this time we got three matches.
2) Using (?i) modifier
Another option is to use the (?i) pattern modifier at the start of the pattern itself which makes whole pattern case insensitive as given below.
How to make partial regex case insensitive?
Specifying Pattern.CASE_INSENSITIVE flag while compiling the pattern makes whole pattern case insensitive. However, if you are using (?i) modifier, you can turn off the case insensitivity by specifying (?-i) modifier in between the pattern which makes part of the regex case insensitive. See below given example.
The first pattern is case sensitive which is the default. The second pattern is case insensitive as we have specified (?i) modifier at the start of the expression so our pattern matches with strings “SECOND” and “second” both.
In the third pattern we have specified (?i) at the start just before “second” (will be matched regardless of the case) but turned it off by specifying (?-i) before “third” (will be matched with exact case). The whole pattern means find all case insensitive words “second” which are followed by case sensitive word “third”. We did a similar thing with our 4th pattern, that is the reason it did not match.
This example is a part of Java RegEx tutorial.
About the author
I have a master’s degree in computer science and over 18 years of experience designing and developing Java applications. I have worked with many fortune 500 companies as an eCommerce Architect. Follow me on LinkedIn and Facebook.