diff --git a/java/src/main/java/com/twitter/twittertext/Validator.java b/java/src/main/java/com/twitter/twittertext/Validator.java index f19364416..602429da2 100644 --- a/java/src/main/java/com/twitter/twittertext/Validator.java +++ b/java/src/main/java/com/twitter/twittertext/Validator.java @@ -4,6 +4,8 @@ package com.twitter.twittertext; +import java.util.List; + /** * A class for validating Tweet texts. */ @@ -36,6 +38,24 @@ public boolean isValidTweet(String text) { return TwitterTextParser.parseTweet(text).isValid; } + /** + * Checks if a given text is a valid hashtag. + * + * @param text text to validate + * @return whether the text is a valid hashtag or not + */ + public boolean isValidHashtag(String text) { + if (text == null) { + return false; + } + + Extractor extractor = new Extractor(); + List extracted = extractor.extractHashtags(text); + + // Should extract the hashtag minus the # sign, hence the .substring(1) + return extracted.size() == 1 && extracted.get(0).equals(text.substring(1)); + } + public static boolean hasInvalidCharacters(String text) { return Regex.INVALID_CHARACTERS_PATTERN.matcher(text).matches(); } diff --git a/java/src/test/java/com/twitter/twittertext/ValidatorTest.java b/java/src/test/java/com/twitter/twittertext/ValidatorTest.java index 9e5cadaae..2b5e7df3f 100644 --- a/java/src/test/java/com/twitter/twittertext/ValidatorTest.java +++ b/java/src/test/java/com/twitter/twittertext/ValidatorTest.java @@ -50,4 +50,17 @@ public void testMutiByteCharacters() { assertTrue(validator.isValidTweet(builder.append(c).toString())); assertFalse(validator.isValidTweet(builder.append(c).toString())); } + + public void testValidHashtags() { + assertTrue(validator.isValidHashtag("#test")); + assertTrue(validator.isValidHashtag("#\u53F0\u7063")); + } + + public void testInvalidHashtags() { + assertFalse(validator.isValidHashtag("#test #test")); + assertFalse(validator.isValidHashtag("#test test")); + assertFalse(validator.isValidHashtag("#test,test")); + assertFalse(validator.isValidHashtag("test")); + assertFalse(validator.isValidHashtag(null)); + } }