File tree Expand file tree Collapse file tree 2 files changed +33
-0
lines changed
main/java/com/twitter/twittertext Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change 44
55package com .twitter .twittertext ;
66
7+ import java .util .List ;
8+
79/**
810 * A class for validating Tweet texts.
911 */
@@ -36,6 +38,24 @@ public boolean isValidTweet(String text) {
3638 return TwitterTextParser .parseTweet (text ).isValid ;
3739 }
3840
41+ /**
42+ * Checks if a given text is a valid hashtag.
43+ *
44+ * @param text text to validate
45+ * @return whether the text is a valid hashtag or not
46+ */
47+ public boolean isValidHashtag (String text ) {
48+ if (text == null ) {
49+ return false ;
50+ }
51+
52+ Extractor extractor = new Extractor ();
53+ List <String > extracted = extractor .extractHashtags (text );
54+
55+ // Should extract the hashtag minus the # sign, hence the .substring(1)
56+ return extracted .size () == 1 && extracted .get (0 ).equals (text .substring (1 ));
57+ }
58+
3959 public static boolean hasInvalidCharacters (String text ) {
4060 return Regex .INVALID_CHARACTERS_PATTERN .matcher (text ).matches ();
4161 }
Original file line number Diff line number Diff line change @@ -50,4 +50,17 @@ public void testMutiByteCharacters() {
5050 assertTrue (validator .isValidTweet (builder .append (c ).toString ()));
5151 assertFalse (validator .isValidTweet (builder .append (c ).toString ()));
5252 }
53+
54+ public void testValidHashtags () {
55+ assertTrue (validator .isValidHashtag ("#test" ));
56+ assertTrue (validator .isValidHashtag ("#\u53F0 \u7063 " ));
57+ }
58+
59+ public void testInvalidHashtags () {
60+ assertFalse (validator .isValidHashtag ("#test #test" ));
61+ assertFalse (validator .isValidHashtag ("#test test" ));
62+ assertFalse (validator .isValidHashtag ("#test,test" ));
63+ assertFalse (validator .isValidHashtag ("test" ));
64+ assertFalse (validator .isValidHashtag (null ));
65+ }
5366}
You can’t perform that action at this time.
0 commit comments