Вот моя попытка подкреплена некоторыми юнит-тестами. Без сомнения, другие придумают превосходное регулярное выражение, подключат их к тесту и опробуют.
Редактировать
Мой оригинальный регулярный оператор выполняет свою работу, но я думаю, что ^[^#]{3}#[^#]+#[^#]{2,}$
от @CarySwoveland в комментариях - это регулярное выражение, поэтому я заменил его на его.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SOExample {
public boolean match(String s) {
String pattern = "^[^#]{3}#[^#]+#[^#]{2,}$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(s);
return m.matches();
}
@Test
public void match_returns_true_for_example_string() {
assertTrue(match("ren#firstname#lastname"));
}
@Test
public void match_returns_false_when_the_first_hash_is_not_the_forth_character() {
assertFalse(match("renX#firstname#lastname"));
}
@Test
public void match_returns_false_when_the_second_hash_is_in_the_last_position_of_the_string() {
assertFalse(match("ren#firstname#"));
}
@Test
public void match_returns_false_when_the_second_hash_is_in_the_second_last_position_of_the_string() {
assertFalse(match("ren#firstname#l"));
}
@Test
public void match_returns_false_when_the_the_two_hashes_do_not_follow_each_other() {
assertFalse(match("ren#firstname##lastname"));
}
}