방법 1 : 편집 Jsoup 소스와는 파서를 공개하거나 거기에 자신 만의 방법을 구현
방법 2 : 간단한 더미 요소를 구문 분석 예외를 잡을 수있어. throw되는 경우 : 쿼리가 유효하지 않습니다. 그렇지 않으면 괜찮습니다. 최고의 솔루션은 아니지만 작동합니다.
private static final Element dummy = new Element(Tag.valueOf("p"), ""); // used for "testparsing"
// ...
public static boolean isValid(String query)
{
if(query == null) // Check for null
return false;
try
{
Selector.select(query, dummy); // Use the querystring on the dummy - returnvalue is not relevant
}
catch(Selector.SelectorParseException | IllegalArgumentException ex) // these exceptions are thrown if something is not ok
{
return false; // If something is not ok, the query is invalid
}
return true; // All ok, query is valid
}
시험 :
System.out.println(isValid(null)); // not valid
System.out.println(isValid("div.abc")); // valid
System.out.println(isValid("p[")); // not valid
System.out.println(isValid("a:matchesxy")); // not valid
System.out.println(isValid("div > a")); // valid
Testresult :
false
true
false
false
true
여기
는 예제