From c5a223503ff6a1d23de5e44137c87016f39c7cc7 Mon Sep 17 00:00:00 2001 From: John Lin Date: Tue, 8 Jan 2019 11:56:14 +0800 Subject: [PATCH] Add useful isValidHashtag() for java The implementation references isValidHashtag() in js and valid_hashtag() in ruby --- .../com/twitter/twittertext/Validator.java | 20 +++++++++++++++++++ .../twitter/twittertext/ValidatorTest.java | 13 ++++++++++++ 2 files changed, 33 insertions(+) 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)); + } }