source

Java에서 String.contains() 메서드에서 regex를 사용하는 방법

itover 2022. 11. 21. 22:19
반응형

Java에서 String.contains() 메서드에서 regex를 사용하는 방법

String에 "stores", "store", "product"라는 단어가 그 순서로 포함되어 있는지 확인하고 싶습니다.

나는 그것을 사용해봤어요.someString.contains(stores%store%product);그리고 또.contains("stores%store%product");

regex를 명시적으로 선언하고 메서드에 전달해야 합니까?아니면 regex를 전달하지 않을 수 있습니까?

String. 포함

String.contains는 String, Period와 함께 동작합니다.regex에서는 동작하지 않습니다.현재 String에 정확히 지정된 String이 표시되는지 여부를 확인합니다.

주의:String.contains는 워드 경계를 체크하지 않고 서브스트링만 체크합니다.

정규식 솔루션

Regex의 파워는String.contains키워드(특히)에 단어 경계를 적용할 수 있기 때문입니다.즉, 키워드를 서브스트링뿐만 아니라 단어로 검색할 수 있습니다.

사용하다String.matches다음 정규식을 사용합니다.

"(?s).*\\bstores\\b.*\\bstore\\b.*\\bproduct\\b.*"

RAW regex(문자열 리터럴로 이루어진 이스케이프를 삭제합니다.위의 문자열을 출력하면 다음과 같습니다).

(?s).*\bstores\b.*\bstore\b.*\bproduct\b.*

\b일치하는 단어를 찾을 수 없도록 단어 경계를 확인합니다.restores store products주의해 주세요.stores 3store_product디짓과 디짓으로 인해 거부당하기도 합니다._단어의 일부로 간주되긴 하지만 이 경우는 자연스러운 텍스트로 나타나지는 않을 것 같습니다.

단어 경계는 양쪽에서 확인되므로 위의 정규식은 정확한 단어를 검색합니다.바꿔 말하면stores stores product검색 중이기 때문에 위의 regex와 일치하지 않습니다.store없이.s.

. 보통 새 행 문자를 제외한 모든 문자와 일치합니다. (?s)맨 처음에.는 예외 없이 임의의 문자와 일치합니다(이 점을 지적해 주신 팀 피에츠커 덕분에).

matcher.find()필요한 걸 할 수 있어예:

Pattern.compile("stores.*store.*product").matcher(someString).find();

간단하게 사용할 수 있습니다.matchesString 클래스의 메서드.

boolean result = someString.matches("stores.*store.*product.*");

문자열에 서브스트링이 포함되어 있는지 regex를 사용하고 있지 않은지 여부를 확인하려면 find()를 사용합니다.

    private static final validPattern =   "\\bstores\\b.*\\bstore\\b.*\\bproduct\\b"
    Pattern pattern = Pattern.compile(validPattern);
    Matcher matcher = pattern.matcher(inputString);
    System.out.print(matcher.find()); // should print true or false.

matches()와 find()의 차이를 주의해 주세요.문자열 전체가 지정된 패턴과 일치하면 matches()는 true를 반환합니다.find()는 지정된 입력 문자열의 패턴과 일치하는 서브스트링을 검색합니다.또한 find()를 사용하면 regex 패턴의 선두에 - (?s.)*, 끝에 .* 등의 매칭을 추가할 필요가 없습니다.

public static void main(String[] args) {
    String test = "something hear - to - find some to or tows";
    System.out.println("1.result: " + contains("- to -( \\w+) som", test, null));
    System.out.println("2.result: " + contains("- to -( \\w+) som", test, 5));
}
static boolean contains(String pattern, String text, Integer fromIndex){
    if(fromIndex != null && fromIndex < text.length())
        return Pattern.compile(pattern).matcher(text).find();

    return Pattern.compile(pattern).matcher(text).find();
}

1. 결과: 참

2. 결과: 참

Java 11에서는 다음을 사용할 수 있습니다.Pattern#asMatchPredicate 결과, 반환하다Predicate<String>.

String string = "stores%store%product";
String regex = "stores.*store.*product.*";
Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();

boolean match = matchesRegex.test(string);                   // true

이 메서드는 다른 String 술어와의 체인을 유효하게 합니다.이것은, 이 메서드의 주된 장점입니다.Predicateand,or ★★★★★★★★★★★★★★★★★」negate★★★★★★★★★★★★★★★★★★.

String string = "stores$store$product";
String regex = "stores.*store.*product.*";

Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();
Predicate<String> hasLength = s -> s.length() > 20;

boolean match = hasLength.and(matchesRegex).test(string);    // false

언급URL : https://stackoverflow.com/questions/15130309/how-to-use-regex-in-string-contains-method-in-java

반응형