# #Hashtag_or_not

In this code golf challenge, you will verify hashtags!

# #What_your_code_should_do

Input is a string. Output a truthy value if it is a valid hashtag, and a falsy value otherwise.

We define a string as a valid Hashtag if ...

• It starts with a hash (#).
• It doesn't have a number right after the hashtag (e.g. #2016USElection isn't a valid hashtag).
• It doesn't have any "special characters" (i.e. any character that isn't an alphabet, underscore (_) or a number).

You can assume that the input only contains ASCII characters. (It would be unfair if we did Unicode too.)

# #Rules

Basic rules apply.

# #Examples

Truthy:

#
#e
#_ABC
#thisisanunexpectedlylongstringxoxoxoxo
#USElection2016


Falsy:

Hello, World!
#12thBday
#not-valid
#alsoNotValid!
#!not_a_hash

• Is # really a valid hashtag? – Adám Jul 18 '16 at 11:35
• Is #öäü valid? – chrki Jul 18 '16 at 12:15
• # is not a valid hashtag by any system, Facebook or Twitter it also breaks the rules set also im not sure #_ABC is valid again on them but im not certain of that. – Martin Barker Jul 18 '16 at 13:23
• I assume an alphabet means ascii uppercase or lowercase letter? i.e. abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ? – Rɪᴋᴇʀ Jul 18 '16 at 14:14
• A # is not a hashtag. It's a hash. It, followed by a string is what social media networks refer to as a hashtag. It's a tag, which starts with a hash. – i-CONICA Jul 18 '16 at 15:43

## Retina, 12 bytes

^#(?!\d)\w*$ Prints 1 for hashtags and 0 otherwise. Try it online! (The first line enables a linefeed-separated test suite.) Not much to explain here, this is quite a literal implementation of the definition: ^ and $ are just anchors ensuring that the match covers the entire string, # checks that the string starts with a #, (?!\d) ensures that the next character isn't a digit (without advancing the regex engine's position), \w* checks that we can reach the end of the string with zero or more letters, digits or underscores.

By default, Retina counts the number of matches of the given regex, which is why this gives 1 for valid hash tags and 0 otherwise.

• In Perl, (?!\d) is (?=\D)... but I don't know how you've written Retina. Is it possible you could use (?\D) without the = and save a byte? (If not, is it worth editing the language so that's doable?) – msh210 Jul 19 '16 at 15:08
• @msh210 (?!\d) is different from (?=\D) in that the latter requires some character after the current position while the former is satisfied with the end of the string. Regardless of that, adjusting the regex flavour is currently not possible (since I'm just handing the regex to .NET's regex engine), but making such changes is on the roadmap somewhere (very far) down the line. – Martin Ender Jul 19 '16 at 15:13
• That said, I don't think I'll make the = optional. The entire (?...) syntax was chosen for extensibility, in that the character after the ? is never optional and determines which kind of group this is, and I don't think I want to give up that extensibility. – Martin Ender Jul 19 '16 at 15:13
• (re your first comment) Duh, of course, I shoulda noted that. But it's irrelevant to this answer. (re your second) Yeah, makes sense. There is after all also (?{ and (?? and (?< (both for capturing groups and for lookbehind) and (?- and (?1 and of course the basic (?:. And maybe some I;ve missed. – msh210 Jul 19 '16 at 15:19

## Perl, 22 bytes

21 bytes code +1 for -p

$_=/^#([a-z_]\w*)?$/i


Prints 1 if it's a valid hashtag, empty string otherwise.

### Usage

perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#'
1
perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#_test'
1
perl -pe '$_=/^#([a-z_]\w*)?$/i' <<< '#1test'


Saved 2 bytes thanks for Martin Ender (and another 4 using his lookaround method)

## Perl, 18 bytes

17 bytes code +1 for -p

Using Martin's lookaround this can be much shorter!

$_=/^#(?!\d)\w*$/

• You copied Martin's one and edited it, right? – user54200 Jul 19 '16 at 6:54
• @MatthewRoh The second answer uses Martin's mechanism yes. He did say I could use it, but I didn't want it to be my main answer as I didn't come up with it myself! I've added it for comparison. Retina still beats Perl easily in this type of challenge! – Dom Hastings Jul 19 '16 at 6:56

# JavaScript (ES6), 25 bytes

s=>/^#(?!\d)\w*$/.test(s)  F = s => /^#(?!\d)\w*$/.test(s)
input.oninput = () => result.innerHTML = input.value ? F(input.value) ? '\ud83d\udc8e' : '\ud83d\udca9' : '\ud83d\udcad';
#input, #result {
vertical-align: middle;
display: inline-block;
}
#input {
line-height: 2em;
}
#result {
font-size: 2em;
}
<input id="input" type="text"/> <span id="result">&#x1f4ad</span>

# C, 80 bytes

Function f() takes the string as an argument and modifies int *b to either 1 or 0 to indicate truthy/falsy.

f(char*p,int*b){for(*b=(*p==35)&&!isdigit(p[1]);*p;++p)*b&=isalnum(*p)||*p==95;}


If the string always has at least one character (i.e. never an empty string), a byte can be shaved off for 79 bytes:

f(char*p,int*b){for(*b=(*p==35)&&!isdigit(p[1]);*++p;)*b&=isalnum(*p)||*p==95;}


# Python 3, 41 bytes

import re
re.compile('#(?!\d)\w*$').match  • This should be absolutely fine. Since match objects are truthy and None is falsey, I think dropping the bool() is okay. – Lynn Jul 19 '16 at 14:42 • Yeah I thought about that, thanks for clarifying it! – Gábor Fekete Jul 19 '16 at 14:44 • This generates truthy value for “#fix me Gábor” too. BTW, I see the rules are getting ignored by others too, but this we used to consider a snippet, which usually is not accepted as answer unless the question explicitly allows them. – manatwork Jul 19 '16 at 14:57 • Thanks, I rewrote it to handle the case you wrote and made it a lambda function. – Gábor Fekete Jul 19 '16 at 15:00 • How about re.compile('#(?!\d)\w*$').match? It’s acceptable to drop the f=, BTW. – Lynn Jul 19 '16 at 16:19

# Brachylog, 55 bytes

"#"|h"#",?b@lL'(eE,@A:"1234567890":"_"c'eE),@A:"_"ce~hL


This uses no regex.

### Explanation

Main predicate, Input (?) is a string

"#"                           ? = "#"
|                             Or
h"#",                         First character of ? is "#"
?b@lL                         L is the rest of the chars of ? lowercased
'(                            It is not possible for any char of L that...
eE,                           Call this char E
@A:"1234567890":"_"c          Concatenate the lowercase alphabet with the digits and "_"
'eE                           E is not a member of that concatenated string
),
@A:"_"c                      Concatenate the lowercase alphabet with "_"
e~hL                         One char of that concatenated string is the first char of L


## Python 3, 103 93 bytes

all((c=='_'or c.isalpha()*i>0)^(i<1and'#'==c)^(c.isdigit()*i>1)for i,c in enumerate(input()))


The # being True killed me here, I had to enumerate the string to avoid an index error on the single character input.

• +1. Nice! I completely forgot the isalpha() method on my py3 answer :D "#" being true, also destroyed me. – Yytsi Jul 18 '16 at 13:59

## PowerShell v2+, 25 bytes

$args-match'^#(?!\d)\w*$'


Using Martin's regex, just wrapped up in PowerShell's -match operator coupled with the input $args. For truthy/falsey values, this will return the string itself on a match (a truthy value) or nothing on a non-match (a falsey value). This is because when a comparison operator is applied against an array, it returns anything that satisfies that operator. A couple examples (wrapped in a [bool] cast to make the output more clear): PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#2016Election') False PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 'Hello, World!') False PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#') True PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '') False PS C:\Tools\Scripts\golfing> [bool](.\hashtag-or-not.ps1 '#USElection2016') True  # Mathematica, 5246 43 bytes Saved 6 9 bytes due to @MartinEnder. StringMatchQ@RegularExpression@"#(?!\d)\w*"  Function. Takes a string as input, and returns True or False as output. Pretty simple, just matches against the regex /#(?!\d)\w*/. • I have reason to believe that this won't work for inputs like hello#world since you don't have the beginning and end string anchors. I don't know Mathematica though so I'm not sure. – Value Ink Jul 18 '16 at 17:21 • All righty, I can live with that. Have your +1 – Value Ink Jul 18 '16 at 20:39 # Dyalog APL, 22 20 bytes Without RegEx: {0≤⎕NC 1↓⍵,⎕A}∧'#'=⊃  -2 thanks to ngn • Oh, wow. There are still people who know APL. It's 37 years since I used it! – Auspex Jul 19 '16 at 10:39 • @Auspex APL is well and alive, but quite few features have been added in those years. – Adám Jul 19 '16 at 11:17 # Python 2, 79 bytes lambda x:x=='#'or(1>x[1].isdigit())&x[1:].replace('_','').isalnum()&('#'==x[0])  First golfing attempt. Ungolfed version: def f(x): if x == '#': return True else: return x[0]=='#' and x[1:].replace('_','').isalnum() and not x[1].isdigit()  • Nice answer, and welcome to the site! – DJMcMayhem Jul 18 '16 at 17:24 # Octave, 375654 43 bytes Thanks to @LuisMendo for removing 8 bytes! @(s)s(1)==35&(isvarname(s(2:end))|nnz(s)<2)  Not very golfy, but very built-inny. Edit: The original code accepted strings with no leading '#'. I guess I should have stuck with regex. Test suite on ideone. ## Python3 - 156 128 bytes lambda n:n=="#"or(n[0]=="#")*all(any([47<ord(c)<58,64<ord(c)<91,ord(c)==95,96<ord(c)<123])for c in n[1:]+"0")*~(47<ord(n[1])<58)  A solution that doesn't use regex. 0 is falsey and every other value is truthy. Thanks to @LeakyNun for saving bytes! • @LeakyNun I had to remove the +0 after n[1:], but sadly, still didn't work :/ Gave false to "#d". – Yytsi Jul 18 '16 at 15:32 • @LeakyNun still doesn't work :( Again, had to remove +0 but fails on "#d". I tested it on Python3 though. Not sure if it will work on Python2 – Yytsi Jul 18 '16 at 15:37 • @LeakyNun Just plain false. – Yytsi Jul 18 '16 at 15:47 • @LeakyNun Throws IndexOutOfRange for "#" and False for "#d". – Yytsi Jul 18 '16 at 16:10 • lambda n:n=="#"or(n[0]=="#")*all(any([47<ord(c)<58,64<ord(c)<91,ord(c)==95,96<ord(c)<123])for c in n[1:]+"0")*~(47<ord(n[1])<58) for 128 bytes. Proof that it works – Leaky Nun Jul 18 '16 at 16:44 # Lua, 5955 54 bytes ## Code s=arg[1]print(load(s:sub(2).."=0")and s:sub(1,1)=="#")  ## How it works: 1. Check if the rest of the characters can be a valud Lua identifier (identifiers in Lua follow the same rules as hashtags.) 2. Check if the first character is a #. Takes input from the command line. Prints true if the string is a valid hashtag, otherwise, it prints nil. # Google Sheets, 30 bytes An anonymous worksheet function that takes input from the cell A1 checks it against the RE2 expression and outputs the result to the calling cell. =RegexMatch(A1,"^#([a-z_]\w*)?  # 05AB1E, 18 bytes Code: ¬'#Qs¦A«¬d_sDžjKQP  Uses the CP-1252 encoding. Try it online!. # Sed 19 + 2 = 21 bytes /^#([a-z_]\w*)?$/Ip


This filters out all non-hashtags and outputs valid hashtags.

Run as sed -rn "/^#$|^#[a-z]\w*$/Ip". Quit with Ctrl + D (send EOF).

# GNU grep, 15 + 2 = 17 bytes

grep -Ei '^#([a-z_]\w*)?$'  ### Test: $ echo '#
#e
#_ABC
#thisisanunexpectedlylongstringxoxoxoxo
#USElection2016
Hello, World!
#12thBday
#not-valid
#alsoNotValid!' | grep -Ei '^#([a-z_][a-z0-9_]*)?$'  Output: # #e #_ABC #thisisanunexpectedlylongstringxoxoxoxo #USElection2016  # Python 3, 97 Bytes 70 Bytes 56 Bytes lambda x:s=x[2:];b=x[1];all(x!="#",[x[0]=="#",any[b.isalpha(),"_"in b],any[s.isalnum(),"_"in s]])  (Code changed) Human readable x=input() if x[0]=="#" and x[1].isalpha() and str(x)[2:].isalnum(): print(True) else: print(False)  • Nice answer, and welcome to the site! Functions are also allowed, so you could shorten this quite a bit with lambda x:all(True==[x[0]=="#",x[1].isalpha(),x[2:].isalpha()]) – DJMcMayhem Jul 18 '16 at 20:46 • No problem, glad I could help! – DJMcMayhem Jul 18 '16 at 21:01 • I hate to be the bringer of bad news, but doesn't this fail for '#', which the OP says is truthy? Won't it also fail if the hashtag contains any underscores, which are false under isalpha? – TheBikingViking Jul 18 '16 at 21:23 • @TheBikingViking sorry, I will try to fix this now – Spammy23 Jul 18 '16 at 21:26 • @TheBikingViking That's not what non-competing means. Non-competing is not an excuse for an invalid submission. The correct procedure is to delete the answer, fix it, then undelete it. – Mego Jul 18 '16 at 22:44 ## Pyke, 19 bytes \#.^It,!It\_D-PRkq|  Try it here! Quick fix for tonight • @kenorb rebooted it, ping me if any more issues – Blue Jul 18 '16 at 22:15 • #123 returns still nothing, shouldn't return 0? – kenorb Jul 18 '16 at 22:25 • Nothing is a boolean false – Blue Jul 18 '16 at 22:25 # Ruby, 16 + 3 1 (n flag) = 19 17 bytes Uses 0 as truthy and nil as falsy. p~/^#(?!\d)\w*$/


Run it as ruby -ne 'p~/^#(?!\d)\w*$/'. Thanks to @manatwork for fixing the bash error when running the program. • Do yourself a favor and always enclose code in single quotes. Otherwise the shell will attempt (or even worse, successfully perform) all kind of expansions. (Regarding the current issue with !, see Event Designators in man bash.) – manatwork Jul 19 '16 at 7:55 # Standard ML, 121118 107 bytes (fn#"#"::a=>(fn x::r=>x> #"@"andalso List.all(fn#"_"=>1=1|c=>Char.isAlphaNum c)a|e=>1=1)a|e=>1=0)o explode;  Try it online! Functional solution without using regex. Declares an anonymous function which is bond to the implicit result identifier it. > val it = fn : string -> bool - it "#valid_hash"; > val it = true : bool  • isAlphaNum$orelse that's rather threatening... – cat Jul 18 '16 at 15:57
• @cat this might be the sole positive thing one can say about such verbose boolean operators as orelse and andalso. – Laikoni Jul 18 '16 at 17:38
• It's like, AlphaNum, orelse!! (orelse what?) – cat Jul 18 '16 at 17:43
• One might consider the o explode at the end to be quite threatening too ... – Laikoni Jul 18 '16 at 17:48
• SML seems quite scary, I don't think I could handle that all day :c – cat Jul 18 '16 at 18:10

# Excel VBA, 54 bytes

Anonymous VBE immediate window function that takes input from cell [A1], checks if the value of the cell matches the Like pattern, and outputs as Boolean to the VBE immediate window

?Not[Left(A1,2)]Like"[#]#"And[A1]Like"[#][_a-zA-z0-9]*


import Data.Char
f(a:r)=a=='#'&&r==""||r!!0>'@'&&all(\c->c=='_'||isAlphaNum c)r


Try it online!

# C#, 92 bytes

s=>s[0]=='#'&s.Length>1&&(s[1]<48|s[1]>57)&s.Skip(1).All(x=>char.IsLetterOrDigit(x)|x=='_');


C# lambda (Predicate) where input is a string and output is a bool.

Try it online!

Try it here.