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 Jan 8, 2019
1 parent 752b947 commit c923cf9
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
22 changes: 22 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,10 @@

package com.twitter.twittertext;

import java.util.List;

import com.twitter.twittertext.Extractor;

/**
* A class for validating Tweet texts.
*/
Expand Down Expand Up @@ -36,6 +40,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 c923cf9

Please sign in to comment.