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

문자열에 “stores”, “store”, “product”라는 단어가 포함되어 있는지 확인하고 싶습니다.

나는 someString.contains(stores%store%product);또한 사용해 보았다.contains("stores%store%product");

정규식을 명시 적으로 선언하고 메서드에 전달해야합니까? 아니면 정규식을 전혀 전달할 수 없습니까?



답변

String.contains

String.contains문자열, 마침표와 함께 작동합니다. 정규식에서는 작동하지 않습니다. 지정된 정확한 문자열이 현재 문자열에 나타나는지 여부를 확인합니다.

참고 String.contains단어 경계를 확인하지 않습니다; 단순히 부분 문자열을 확인합니다.

정규식 솔루션

Regex는 String.contains다른 것들 중에서도 키워드에 단어 경계를 적용 할 수 있으므로 보다 강력 합니다. , 하위 문자열이 아닌 단어로 키워드를 검색 할 수 있습니다 .

String.matches다음 정규식과 함께 사용하십시오 .

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

RAW 정규식 (문자열 리터럴에서 수행 된 이스케이프 제거-위의 문자열을 인쇄 할 때 얻는 것입니다) :

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

\b당신이 일치하지 않는 그래서 단어 경계를 검사, restores store products. 참고 stores 3store_product도 자리 때문에 거부되고 _단어의 일부로 간주된다,하지만이 경우 자연 텍스트로 표시 의심한다.

양쪽에 대해 단어 경계가 확인되므로 위의 정규식은 정확한 단어를 검색합니다. 즉, stores stores product이없는 단어 store를 검색하기 때문에 위의 정규식과 일치하지 않습니다 s.

.일반적으로 여러 줄 바꾸기 문자를 제외한 모든 문자와 일치합니다 . 처음에는 예외없이 모든 문자와 일치합니다 (이 점을 지적한 Tim Pietzcker에게 감사드립니다).(?s).


답변

matcher.find()필요한 일을합니다. 예:

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


답변

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

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


답변

문자열에 하위 문자열이 포함되어 있는지 정규식을 사용하지 않는지 확인하려면 가장 가까운 방법은 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.

match ()와 find ()의 차이점에 유의하십시오. 전체 문자열이 주어진 패턴과 일치하면 matches ()가 true를 반환합니다. find ()는 주어진 입력 문자열의 패턴과 일치하는 부분 문자열을 찾으려고합니다. 또한 find ()를 사용하면 정규식 패턴의 시작 부분에-(? 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.result : 참


답변