Skip to content

Commit

Permalink
Add useful isValidHashtag() for java
Browse files Browse the repository at this point in the history
The implementation references isValidHashtag() in js and valid_hashtag() in ruby
  • Loading branch information
johnlinp committed Feb 16, 2019
1 parent 752b947 commit c5a2235
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
20 changes: 20 additions & 0 deletions java/src/main/java/com/twitter/twittertext/Validator.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

package com.twitter.twittertext;

import java.util.List;

/**
* A class for validating Tweet texts.
*/
Expand Down Expand Up @@ -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<String> 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();
}
Expand Down
13 changes: 13 additions & 0 deletions java/src/test/java/com/twitter/twittertext/ValidatorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

0 comments on commit c5a2235

Please sign in to comment.