text:
Find numbers within the Copeland–Erdős constant
Background
The Copeland–Erdős constant is the concatenation of "0." with the base 10 representations of the prime numbers in order. Its value is
0.23571113171923293137414...

See also OEIS A033308.
Copeland and Erdős proved that this is a normal number. This implies that every natural number can be found at some point in the decimal expansion of the Copeland-Erdős  constant.
The challenge
Given a positive integer, express it in base 10 (without leading zeros) and output the index of its first appearance within the sequence of decimal digits of the Copeland–Erdős constant.
Any reasonable input and output format is allowed, but input and output should be in base 10. In particular, the input can be read as a string; and in that case it can be assumed not to contain leading zeros.
Output may be 0-based or 1-based, starting from the first decimal of the constant.
The actual results may be limited by data type, memory or computing power, and thus the program may fail for some test cases. But:

It should work in theory (i.e. not taking those limitations into account) for any input.
It should work in practice for at least the first four cases, and for each of them the result should be produced in less than a minute.

Test cases
Output is here given as 1-based.
13       -->         7   # Any prime is of course easy to find
997      -->        44   # ... and seems to always appear at a position less than itself
999      -->      1013   # Of course some numbers do appear later than themselves
314      -->       219   # Approximations to pi are also present
31416    -->     67858   # ... although one may have to go deep to find them
33308    -->     16304   # Number of the referred OEIS sequence: check
36398    -->     39386   # My PPCG ID. Hey, the result is a permutation of the input!
1234567  -->  11047265   # This one may take a while to find

Seemingly related, but actually quite different.

Okay, so what's the winning criterion?

Considering the detailed rules regarding I/O, I'm going to assume this is code golf and apply the tag. I hope this is what you had in mind.

@Dennis Yes, sorry, I forgot. Thanks for editing

Related Find the number in the Champernowne constant

05AB1E, 14 bytes
Uses 0-indexed output. Prime functions in osabie are very inefficient. Code:
[NØJD¹å#]¹.Oð¢

Explanation:
[       ]        # Infinite loop...
 N               # Get the iteration value
  Ø              # Get the nth prime
   J             # Join the stack
    D            # Duplicate this value
     ¹å#         # If the input is in this string, break out of the loop
         ¹.O     # Overlap function (due to a bug, I couldn't use the index command)
            ð¢   # Count spaces and implicitly print

Uses the CP-1252 encoding. Try it online!.

Python 2, 64 bytes
f=lambda n,k=2,m=1,s='':-~s.find(`n`)or f(n,k+1,m*k*k,s+m%k*`k`)

Returns the 1-based index. Test it on Ideone.

Jelly, 17 bytes
ÆRDFṡL}i
Ḥçßç?
çD

Returns the 1-based index. Try it online! or verify most test cases.
I've verified the last test case locally; it took 8 minutes and 48 seconds.
How it works
çD        Main link. Argument: n (integer)

 D        Decimal; yield A, the array of base 10 digits of n.
ç         Call the second helper link with arguments n and A.

Ḥçßç?     Second helper link. Left argument: n. Right argument: A.

Ḥ         Unhalve; yield 2n.
    ?     If...
   ç        the first helper link called with 2n and A returns a non-zero integer:
 ç            Return that integer.
          Else:
  ß           Recursively call the second helper link with arguments 2n and A.

ÆRDFṡL}i  First helper link. Left argument: k. Right argument: A.

ÆR        Prime range; yield the array of all primes up to k.
  DF      Convert each prime to base 10 and flatten the resulting nested array.
     L}   Yield l, the length of A.
    ṡ     Split the flattened array into overlapping slices of length l.
       i  Find the 1-based index of A in the result (0 if not found).

Alternate version, 11 bytes (non-competing)
ÆRVw³
ḤÇßÇ?

The w atom did not exist when this challenge was posted. Try it online!
How it works
ḤÇßÇ?  Main link. Argument: n (integer)

Ḥ      Unhalve; yield 2n.
    ?  If...
   Ç     the helper link called with argument 2n returns a non-zero integer:
 Ç         Return that integer.
       Else:
  ß      Recursively call the main link with argument 2n.

ÆRVw³  Helper link. Argument: k (integer)

ÆR     Prime range; yield the array of all primes up to k.
  V    Eval; concatenate all primes, forming a single integer.
    ³  Yield the first command-line argument (original value of n).
   w   Windowed index of; find the 1-based index of the digits of the result to
       the right in the digits of the result to the left (0 if not found).

Actually, 19 bytes
╗1`r♂Pεj╜@íu`;)╓i@ƒ

Takes a string as input and outputs the 1-based index of the substring
Try it online!
Explanation:
╗1`r♂Pεj╜@íu`;)╓i@ƒ
╗                    push input to register 0
  `r♂Pεj╜@íu`;)      push this function twice, moving one copy to the bottom of the stack:
   r♂Pεj               concatenate primes from 0 to n-1 (inclusive)
        ╜@íu           1-based index of input, 0 if not found
1              ╓     find first value of n (starting from n = 0) where the function returns a truthy value
                i@   flatten the list and move the other copy of the function on top
                  ƒ  call the function again to get the 1-based index

Husk, 6 bytes
€ṁdİpd

Try it online!
Prime number infinite list babyyyyy

Great!  "prime related functions are generally terrible for time based challenges in husk" - apparently not in this instance...!

@DominicvanEssen This challenge is pretty generous in that regard.

Julia, 55 bytes
\(n,s="$n",r=searchindex(n|>primes|>join,s))=r>0?r:3n\s

Returns the 1-based index. Completes all test cases in under a second. Try it online!

Is there a reason why you shift the primes upper bound by 3 and not e.g. by 2? Also, is there a way to extend it to work for 0 on input shorter than ...=r>0?r:3(n+9)\s?

3 was slightly faster than 2 in my tests and didn't increase the byte count. For input 0, you could use -~n instead, but it would be a lot slower.

Thanks, -~3n\s (== (3n+1)\s) is good enough.

Pyth, 17 bytes
 fhJxs`MfP_YSTz2J

Leading space is important.
Test suite.

@LuisMendo You could test it for me.

J, 37 bytes
(0{":@[I.@E.[:;<@":@p:@i.@]) ::($:+:)

Input is given as a base 10 integer and the output uses zero-based indexing.
Usage
   f =: (0{":@[I.@E.[:;<@":@p:@i.@]) ::($:+:)
   f 1
4
   f 13
6
   f 31416
67857

Explanation
This first call treats the verb as a monad, however subsequent calls which may occur recursively treat it as a dyad.
0{":@[I.@E.[:;<@":@p:@i.@]  Input: n on LHS, k on RHS
                         ]  Get k
                      i.@   Get the range [0, 1, ..., k-1]
                   p:@      Get the kth prime of each
                ":@         Convert each to a string
              <@            Box each string
           [:;              Unbox each and concatenate to get a string of primes
     [                      Get n
  ":@                       Convert n to a string
      I.@E.                 Find the indices where the string n appears in
                            the string of primes
0{                          Take the first result and return it - This will cause an error
                            if there are no matches

(...) ::($:+:)  Input: n on RHS, k on LHS
(...)           Execute the above on n and k
      ::(    )  If there is an error, execute this instead
           +:   Double k
         $:     Call recursively on n and 2k

Can you prove that this works?

@LeakyNun Oh yes that's true, it technically only works for the test cases but it might not be found in the first n primes.

It doesn't work for n = 1 since the first prime is 2 and you need the first five primes to get the first occurrence of a 1.

Ruby -rprime, 48 bytes
0-based.
->n{s=""
Prime.find{s<<_1.to_s=~/#{n}/}
$`.size}

Attempt This Online!

Raku, 45 bytes
{{$~={$_ x.is-prime}(++$)}...*~~/$_/;$/.from}

Try it online!
Really had to dig deep to bring the byte count way down here.  The code  generates a warning, but oh well!
The first bracketed expression generates strings consisting of the concatenation of successive primes.  ++$ increments an anonymous state variable, and that number is passed to an anonymous function { $_ x .is-prime }, which replicates the stringified number once if it's prime, and zero times (ie, to an empty string) if it isn't.  That string is appended to another anonymous state variable that keeps the concatenation of all primes seen so far with $ ~=.  The sequence looks like 2, 23, 23, 235, 235, 2357, 2357, 2357, 2357, 235711, ..., with a repeated element whenever there isn't a prime.  Very inefficient!
The sequence terminates when the ending condition * ~~ /$_/ is met; that is, when the concatenated string of primes matches the input number interpolated into a regex.  That has the side effect of storing the resulting Match object into $/.  Then the function just returns $/.from, the starting position of the match in the string of primes.

PowerShell v2+, 90 bytes
for($a="0.";!($b=$a.IndexOf($args)+1)){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){$a+=$i}}$b-2

Combines the logic of my Find the number in the Champernowne constant answer, coupled with the prime generation method of my Print the nth prime that contains n answer, then subtracts 2 to output the index appropriately (i.e., not counting the 0. at the start).
Takes input as a string. Finds the 999 one in about seven seconds on my machine, but the 33308 one in quite a bit longer (edit - I gave up after 90 minutes). Should theoretically work for any value up to index [Int32]::Maxvalue aka 2147483647, as that's the maximum length of .NET strings. Will likely run into memory issues long before that happens, however.


text:
JSON tips: filter objects from array of objects where object name is alpha

What could be the shortest code for filtering the following array in Javascript without any library?
My code is:
filtered_obj = _.where(obj, { name: "Alpha" });

This uses a JS library called underscore.
Test case:
objs = [{'id':1,'name':'Alpha'},{'id':2,'name':'Beta'},
{'id':3,'name':'Gamma'},{'id':4,'name':'Eta'},
{'id':5,'name':'Alpha'},{'id':6,'name':'Zeta'},
{'id':7,'name':'Beta'},{'id':8,'name':'Theta'},
{'id':9,'name':'Alpha'},{'id':10,'name':'Alpha'}];

filtered_obj =[{'id':1,'name':'Alpha'},{'id':5,'name':'Alpha'},
{'id':9,'name':'Alpha'},{'id':10,'name':'Alpha'}]

@closevoter: Questions asking tips about golfing code are on-topic.

@LeakyNun It sure is, but without some proof of actual research from the OP, we can't say if it only is a genuine [tag:tips] question or a [tag:do-my-homework] one. Might be why someone closevoted

I used underscore which is filtered_obj = _.where(obj, { name: "Alpha" }); then I am looking for not using any library.

I'm voting to close this question as off-topic because I agree with @Katenkyo and think this is a homework question in disguise.

@muddyfish Go ahead. Appreciate the help anyways.

Not sure whether is homework or should be closed, but certainly I would expect a tip to be formulated in more generic style.

45 bytes
filtered_obj=objs.filter(n=>n.name=='Alpha');

This uses the filter function for arrays.
Ideone it!

please look into it http://ideone.com/p3cENn

Because I'm using spidermonkey instead of rhino.

How did you calculate the number of bytes for the solution as 45 bytes?

by counting the number of characters in filtered_obj=objs.filter(n=>n.name=='Alpha');.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
#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 code-golf 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 Why not??

Is #öäü valid?

Should the empty string return falsy? Or are we allowed to require at least one character?

# 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.

I assume an alphabet means ascii uppercase or lowercase letter? i.e. abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ?

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.

Will we receive empty string as an input?

Is printing nothing equals to False?

@LeakyNun No, You won't.

This is similar to the definition of a valid identifier in many languages. Not sure if abusing eval would be possible though.

You should either allow - or disallow both - and _, in my opinion.

@Peanut Why? The challenge works perfectly well as is, and _ is treated as a word character in a lot of contexts while - almost never is.

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 (?!\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.

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.

(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.

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?

@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!

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"/> &#x1f4ad

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.

Yeah I thought about that, thanks for clarifying it!

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.

Thanks, I rewrote it to handle the case you wrote and made it a lambda function.

How about re.compile('#(?!\d)\w*$').match? It’s acceptable to drop the f=, BTW.

Oh, nice idea, it will be then a function too!

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.

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, 52 46 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.

All righty, I can live with that. Have your +1

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".

@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

@LeakyNun Just plain false.

@LeakyNun Throws IndexOutOfRange for "#" and False for "#d".

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

@LeakyNun Now that works. The return values are pretty odd: "12" --> 0, "#" --> true, "#ab" --> -1, "#1b" --> -2. Can I just treat every output other output than "True" as falsey?

Here is the meta post for reference.

@LeakyNun Thanks! I managed to golf my solution down to 131 bytes, but yours is currently better, so I'll take it.

No, Falsey is 0, every other value will be truthy, in this case.

@LeakyNun Oops, I'll fix it, thanks!

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 APL is well and alive, but quite few features have been added in those years.

Octave, 37 56 54 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.

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!

Lua, 59 55 54 bytes
Code
s=arg[1]print(load(s:sub(2).."=0")and s:sub(1,1)=="#")

How it works:

Check if the rest of the characters can be a valud Lua identifier (identifiers in Lua follow the same rules as hashtags.)
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!.

Standard ML, 121 118 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 this might be the sole positive thing one can say about such verbose boolean operators as orelse and andalso.

It's like, AlphaNum, orelse!! (orelse what?)

One might consider the o explode at the end to be quite threatening too ...

orelse explode D:

SML seems quite scary, I don't think I could handle that all day :c

Pyke, 19 bytes
\#.^It,!It\_D-PRkq|

Try it here!
Quick fix for tonight

@kenorb rebooted it, ping me if any more issues

#123 returns still nothing, shouldn't return 0?

Nothing is a boolean false

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()])

No problem, glad I could help!

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 sorry, I will try to fix this now

It might be worth marking your answer as non-competing until it is fixed, to prevent any downvoting.

@TheBikingViking Is it okay now?

Try running it past all the test cases, and see if it returns the correct output.

@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 Ah, okay, Thanks for pointing that out.

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

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).

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.)

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]*

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

Try it online!

Java 8, 57 54 28 bytes
s->s.matches("#(?!\\d)\\w*")

Port of Martin Ender's Retina answer to save a few bytes and match added test cases.
Not that String#matches always matches the entire String, so no need for ^...$.
Try it here.

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!

Lua, 39 bytes
print(arg[1]:match("^#[%a_][%a_%d]*$"))

Straightforward copypasta of match description. Outputs falsy nil if not hashtag, outputs truthly hashtag back otherwise.
Can be shortened for one more byte by using find if outputing list of two values (which is truthly) doesn't break rules.

I think this won't match a # on its own.

@MartinEnder, of course. It shouldn't. None of the top answers do that either. Also http://codegolf.stackexchange.com/questions/85619/hashtag-or-not/85797#comment210296_85619

Whether # is a hashtag on Twitter or Facebook is irrelevant to this challenge. The specification is very clear on the fact that # should be considered a hashtag for the purposes of this challenge. And while I haven't checked all of the answers, all I did check do accept # as a hashtag, so I'm not sure which top answers you're referring to.

Clojure, 130 135 132 bytes

+5 bytes to deal with an NPE that happened when the string consisted of only a hashtag.
-2 bytes by using Character/isLetterOrDigit.

(fn[s](let[[h & r]s n(map int r)](and(= h\#)(not(<= 48(or(first n)0)57))(every? #(or(Character/isLetterOrDigit^long %)(= 95 %))n))))

Ungolfed:
(defn hashtag? [s]
  (let [[h & r] s
        codes (map int r)]
    (and (= h \#)
         (not (<= 48 (or (first codes) 0) 57))
         (every?
           #(or (Character/isLetterOrDigit ^long %)
                (= 95 %))
           codes))))

Whoops, this actually gives a NPE for "#". Give me a sec.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Select the word around the given index in a given string
In the most common contemporary graphical desktop interfaces, when you perform double-click in a text, the word around your cursor in the text will be selected.†
For example, let | be your cursor in abc de|f ghi.
Then, when you double click, the substring def will be selected.
Input/Output
You receive two inputs:

a string and
an integer.
Your task is to return the word‐substring of the string around the index specified by the integer.

Your cursor can be right before or right after the character in the string at the index specified.
If you use right before, please specify in your answer.
Specifications

The index is guaranteed to be inside a word, so no edge cases like abc |def ghi or abc def| ghi.
The string will only contain printable ASCII characters (from U+0020 to U+007E).
The word word is defined by the regex (?<!\w)\w+(?!\w), where \w is defined by [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_], or “alphanumeric characters in ASCII including underscore”.
The index can be either 1‑based or 0‑based.
If you use are 0‑based index, please specify it in your answer.

Test cases
The cursor position visualization is for demonstration purpose only; it is not a required output.
The cursor is indicated right after the index specified.
Here, the sample string indices are 1‑based.

sample
index
visualization
output

abc def
2
ab|c def
abc

abc def
5
abc d|ef
def

abc abc
2
ab|c abc
abc

ab cd ef
4
ab c|d ef
cd

ab   cd
6
ab   c|d
cd

ab!cd
1
a|b!cd
ab

†) This feature has more complicated properties, but they are not required to be implemented for this challenge.

Can the string contain newlines?

@orlp The challenge was edited to restrict the input to printable ASCII so the input will not contain newlines.

Your testcases do not contain any other delimiters than spaces. What about a word like we're?

What should "ab...cd", 3 return?

@Titus "The index is guaranteed to be inside a word"

V, 10, 9 7 bytes
À|diwVp

Try it online!
This answer uses 1-based indexing.
This could be shorter if we do exactly what the title says: "Select the word around the given index in a string". We could do
À|viw

Which literally selects the word, but unfortunately doesn't change the output at all. So we need a little workaround to make it work by cutting it into a register, deleting the rest of the text, then pasting the register back in.
Explanation:
À|          " Jump the position of argument 1
  diw       " (d)elete (i)nside this (w)ord.
     V      " Select this line
      p     " And replace it with the word we just deleted

C, 104 bytes
p[99];i,d;main(l){for(scanf("%d",&i);scanf("%[^a-zA-Z0-9_]%[a-zA-Z0-9_]%n",&d,&p,&l),i>l;i-=l);puts(p);}

Expects the input on stdin to be the 0-based index followed by one space or newline, followed by the string. Maximal length for a word is 99 characters. E.g.:
2 abc def

It's really cool to see C and perl tied on a string based challenge. :D

Can the input string have longer than 100 characters?

@LeakyNun Yes, but one word can not be longer than 100 characters.

Do you feel like putting that requirement inside your answer?

@DrGreenEggsandIronMan Too bad I had to fix my answer because it was delimited on whitespace :(

I think you can use [\w_] to replace [a-zA-Z0-9_]?

C (gcc), 94 bytes
f(n,p)char*p;{for(p+=n-1;isalnum(*p)|*p==95&&n--;--p);for(;isalnum(*++p)|*p==95;putchar(*p));}

Zero-indexed, defines a function taking the index, then the string.

I think isalnum(*++p)|*p==95 is undefined behavior.

@owacoder It is, but what matters is that gcc spits out an executable that works. *++p^95?isalnum(*p):1 is one byte longer, but works on every compiler.

I assume the leading space is a typo? Also, here's a lazy IDEone link.

isalnum(*++p)||*p==95 also works, for an added one byte.

@FryAmTheEggman Yes it is, fixed now.

@orlp - f(p,n)char*p;{for(;n--&&isalnum(p[n])|p[n]==95;);for(p+=n;isalnum(*++p)|*p==95;putchar(*p));} is one byte shorter.

Retina, 22

(1)+¶(?<-1>.)*\b|\W.+

Try it online! or verify all test cases. The regular program takes the cursor position in unary followed by a newline and then the string. The test suite has additional code to run in per line mode, and uses a \ as a delimiter, and it uses decimal, for convenience.
Uses balancing groups to find the cursor position, then backtracks up to a word boundary. Deletes the text up to the word, and then after the word.

Python 2, 70 66 bytes
import re
f=lambda x,y,r=re.split:r('\W',x[:y])[-1]+r('\W',x[y:])[0]

Splits the string by non-word separators, once on the original string up to the cursor index, then on the string beginning at the cursor index. Returns the last element of the left split plus the first element of the right split.
Thanks to Leaky Nun for saving 4 bytes!

For non-recursive lambdas, you can omit the f= to 'save' two more bytes.

Pyth, 16 bytes
+e=:.<+QbE"\W"3h

       Q            first input (string)
      + b           plus newline
    .<   E          rotate left by second input (number)
   :      "\W"3     split on regex \W, non-word characters
  =                 assign to Q
 e                  last element
+              hQ   plus first element

Try it online

Ruby, 41 31 bytes
Try it online!
-10 bytes from @MartinEnder
->s,i{s[/\w*(?<=^.{#{i}})\w*/]}

JavaScript (V8), 44 bytes
(i,x)=>RegExp(`\\w*(?<=.{${i}})`).exec(x)[0]

Try it online!
This is longer than an existing JS solution, but I don't actually understand the approach it uses, and I wrote this prior to seeing that solution. Hopefully this is different enough to be interesting :P
Code explanation, so the same fate is not befallen upon ye
(i,x)=>                                 take i (number) and x (string)
       RegExp(`...${i}...`)             construct a regex with i in it
                           .exec(x)[0]  return the first result of that regex on the string

\w*(?<=.{i}) constructed regex
\w*          match an entire word
   (?<=    ) if the end of the word comes after
       .{i}  at least i characters

43 bytes if you curry but who really cares

C, 115 bytes
Function f() requires the string and index (1-indexed) as parameters and prints the result to stdout. Cursor should be after the specified character.
f(char*p,int n){char*s=p+n;for(;s>=p&&isalnum(*s)+(*s==95);--s);for(p=s+1;*p&&isalnum(*p)+(*p==95);putchar(*p++));}

JavaScript (ES6), 57 bytes
f=(s,n)=>s.slice(0,n).match(/\w*$/)+s.slice(n).match(/\w*/)

Simply slices the string at the cursor point (which is before the 0-indexed character, which works out the same as after the 1-indexed character), then extracts and concatenates the adjacent word fragments. Even returns a sensible result when the cursor is at the start, end, or nowhere near a word.

Do you need the * in the last regex?

@CharlieWynn Yes, otherwise the second testcase would only return de.

whoops, got unlucky with the tests I ran

Pyke, 19 bytes
#Q;cjmli<i+s)lttjR@

Try it here!
Uses Q; as a no-op to make sure the first input is placed correctly
#          )   -  first where
   c           -       input.split()
    ml         -      map(len, ^)
      i<       -     ^[:i]
        i+     -    ^+[i]
          s    -   sum(^)
            lt - len(^)-2

I'm having a 504 error when I click your link.

@LeakyNun Yeah, I killed it by accident whilst writing which is why I had the localhost link, it'll come back

Try it here!

Your program seems to be outputting N where the Nth word is the one selected, but we need the full word

Java 8, 86 78 bytes
(s,p)->{for(String t:s.split("\\W"))if((p-=t.length()+1)<0)return t;return"";}

Ungolfed with test cases:
class Indexer {
    public static String f(String s, int p) {
        for(String t : s.split("\\W"))
            if((p -= t.length()+1) < 0)
                return t;
        return "";
    }

    public static void main(String[] args) {
        System.out.println(f("abc def",2));
        System.out.println(f("abc def",5));
        System.out.println(f("abc abc",2));
        System.out.println(f("ab cd ef",4));
        System.out.println(f("ab   cd",6));
        System.out.println(f("ab!cd",1));
    }
}

Splits the string by non-alphanumeric characters, then keeps subtracting the length of each substring, plus 1, from the specified position, until it becomes negative. Since any repeating non-alphanumerics get represented as empty string, the subtraction logic is significantly easier.
This code isn't extensively tested, so I'd like to see if someone can break this. Also, considering that this is Java code, how is this not the longest answer here? :P

I know it's been almost three years, but (s,p)-> can be s->p-> by using a currying lambda expression (i.e. java.util.function.Function<String, java.util.function.Function<String, String>> f). In addition, String could be var now if switched to Java 10, although that wasn't available at the time of course. Regardless, nice answer. I see I've already updated it somewhere in the past. :)

Ruby, 30 bytes
->s,n{s[/.{#{n}}\w+/][/\w+$/]}

Try it online!
A different approach, only 1 byte shorter and 3 years later. Why not?

Clojure, 92 bytes
(fn[x k](let[[u i](map #(re-seq #"\w+"(apply str %))(split-at k x))](str(last u)(nth i 0))))

First, splits input string at position k into two strings. Then for these strings find occurrences of "\w+" and return them as list. Then concatenate the last element of first list and the first element of second list.
See it online: https://ideone.com/Dk2FIs

JavaScript (ES6), 52 bytes
(s,n)=>RegExp(`^.{0,${n}}(\\W+|^)(\\w+)`).exec(s)[2]

const F = (s,n) => RegExp(`^.{0,${n}}(\\W+|^)(\\w+)`).exec(s)[2]

class Test extends React.Component {
    constructor(props) {
        super(props);
        const input = props.input || '';
        const index = props.index || 0;
        this.state = {
            input,
            index,
            valid: /\w/.test(input),
        };
    }
    onInput = () => {
        const input = this.refs.input.value;
        const index = Math.min(+this.refs.index.value, input.length);
        this.setState({
            input,
            index,
            valid: /\w/.test(input),
        });
    }
    render() {
        const {input, index, valid} = this.state;
        return (

                { this.props.children }

                    <input ref="input" type="text" onInput={this.onInput} value={input} />
                    <input ref="index" type="number" onInput={this.onInput} min="1" max={input.length} value={index} />

                {valid && [
                    {F(input, index)}	,

{input.slice(0, index)}|{input.slice(index)}
	,
                ]}

        );
    }
}

class TestList extends React.Component {
    constructor(props) {
        super(props);
        this.tid = 0;
        this.state = {
            tests: (props.tests || []).map(test => Object.assign({
                key: this.tid++
            }, test)),
        };
    }
    addTest = () => {
        this.setState({
            tests: [...this.state.tests, { key: this.tid++ }],
        });
    }
    removeTest = key => {
        this.setState({
            tests: this.state.tests.filter(test => test.key !== key),
        });
    }

    render() {
        return (

                        Test
                        Output
                        Diagram

                        {
                            this.state.tests.map(test => (
                                <Test key={test.key} input={test.input} index={test.index}>
                                    <button onClick={() => this.removeTest(test.key)} style={{
                                        verticalAlign: 'middle',
                                    }}>-</button>
                                </Test>
                            ))
                        }

                            <button onClick={this.addTest} style={{
                                width: '100%',
                            }}>Add test case</button>

        );
    }
}

ReactDOM.render(<TestList tests={[
    { input: 'abc def', index: 2 },
    { input: 'abc def', index: 5 },
    { input: 'abc abc', index: 2 },
    { input: 'ab cd ef', index: 4 },
    { input: 'ab   cd', index: 6 },
    { input: 'ab!cd', index: 1 },
]} />, document.body);
input[type="number"] {
  width: 3em;
}
table {
  border-spacing: 0.5em 0;
  border-collapse: separate;
  margin: 0 -0.5em ;
}
td, input {
    font-family: monospace;
}
th {
  text-align: left;
}
tbody {
  padding: 1em 0;
}
pre {
  margin: 0;
}

Why (\\W+|^) not (\\W|^)

Lua, 71 67 Bytes
Woohoo, Lua isn't the longest solution! Still one byte behind python, but don't know how to golf this down. Indexes are 1-based.
Thanks to @LeakyNun reminding me the existence of string.match, saved 4 bytes
g,h=...print(g:sub(1,h):match"[%a_]*$"..g:sub(h+1):match("[%a_]+"))

Old 71
Note: the explanations are still based on this one, because it also applies to the new one, but contains some extra informations on gmatch
g,h=...print(g:sub(1,h):gmatch"[%a_]*$"()..g:sub(h+1):gmatch"[%a_]*"())

Explanation
First, we unpack the arguments into g and h because they are shorter than arg[x]
g,h=...

Then, we construct our output, which is the concatanation of the part before the cursor and after it.
The first part of the string is
g:sub(1,h)

We want to find the word at the end of this one, so we use the function string.gmatch
:gmatch"[%a_]*$"

This pattern match 0..n times the character set of alphabet+underscore at the end of the string. gmatch returns an iterator on its list of match in the form of a function (using the principle of closure), so we execute it once to get the first part of our word
g:sub(1,h):gmatch"[%a_]*$"()

We get the second part of our word by the same way
g:sub(h+1):gmatch"[%a_]*"())

The only difference being we don't have to specify we want to match at the start of the string (using [^%a_]*), as it will be the match returned by the iterator when it's called the first time.

g:sub(h+1):match"^[%a_]*"?

@LeakyNun totally forgot the existence of match \o/ saves lot of bytes, thanks

@LeakyNun both indices and indexes are correct ^^

I don't care, still -1 for "indexes".

Why don't we need the ^ anchor?

@LeakyNun because the first match will always be placed at the first of the sentence, thus being matched and returned the first (iterators work in FIFO ^^)

But match isn't an iterator, right

@LeakyNun Yes, but match stops as soon as it match for the first time, leaving us with the same result as gmatch()()

JavaScript (ES 6), 4342 Bytes
s=>n=>s.replace(/\w*/g,(x,y)=>y<n?s=x:0)&&s

JavaScript (ES 3), 65 Bytes
function(s,n){s.replace(/\w*/g,function(x,y){y<n?s=x:0});alert(s)}

05AB1E, 14 bytes
ð«._DžjмS¡Á2£J

Port of @AndersKaseorg's Pyth answer.
1-indexed like the challenge test cases.
Try it online or verify all test cases.
Explanation:
ð«              # Append a space to the (implicit) input-String
  ._            # Rotate this string the (implicit) input-integer amount of times
                #  towards the left
     D          # Duplicate this string
      žjм       # Remove [a-zA-Z0-9_] from the string
         S¡     # Split the rotated string by each of the remaining characters
           Á    # Rotate the resulting list once towards the right
            2£J # And only leave the first two items, joined together
                # (which is output implicitly)

Perl 6, 34 bytes
->\b{&{first *.to>b,m:g/<<\w+>>/}}

Try it online!
Anonymous codeblock that takes input curried, like f(n)(string).
Explanation:
->\b{                            }   # Anonymous code block that takes a number
     &{                         }    # And returns another code block that
       first       ,m:g/<<\w+>>/     # Finds the first word in the input
             *.to>b                  # Where the start is after the number

APL(NARS), 58 chars, 116 bytes
{m←⎕A,⎕a,⎕D,'_'⋄↑v⊂⍨m∊⍨v←⍵↓⍨¯1+⍵{⍵≤1:⍵⋄m∊⍨⍵⊃⍺:⍺∇⍵-1⋄⍵+1}⍺}

⍵{⍵≤1:⍵⋄m∊⍨⍵⊃⍺:⍺∇⍵-1⋄⍵+1}⍺ find where start the string...How to use and test:
  f←{m←⎕A,⎕a,⎕D,'_'⋄↑v⊂⍨m∊⍨v←⍵↓⍨¯1+⍵{⍵≤1:⍵⋄m∊⍨⍵⊃⍺:⍺∇⍵-1⋄⍵+1}⍺}
  2 f 'abc def'
abc
  5 f 'abc def'
def
  2 f 'abc abc'
abc
  4 f 'ab cd ef'
cd
  1 f 'ab!cd'
ab
  6 f 'ab   cd'
cd

Jelly, 12 bytes
Żṙe€ØW¬œpƊ.ị

Try it online!
Port of Anders Kaseorg's Pyth answer.
Ż               Prepend a zero as a buffer between the first and last words,
 ṙ              then rotate left by the index.
       œpƊ      Partition that result around
   €  ¬         elements which are not
  e ØW          word characters,
          .ị    then take the last and first slices
                and smash-print them together.

Original:
Jelly, 14 bytes
xðe€ØW¬Ä÷Ɗ=ị@¥

Try it online!
  e€ØW            For each element, is it a word character?
       Ä          Take the cumulative sum
      ¬           of the negations
        ÷Ɗ        and divide by the original Booleans.
          =       For each value in the result, is it equal to
           ị@¥    the one at the index?
xð                Filter the string to truthy positions.

MATL, 16 15 bytes
'\w+'5B#XXi>)1)

Cursor is 1-indexed and after the character (as in the test cases).
Try it online! Or verify all test cases.
'\w+'    % Push string to be used as regex pattern
5B#XX    % Take input string implicitly. Apply regex. Push matches and ending indices
i>       % Take input number. Compare with obtained ending indices. Gives true for
         % ending indices that exceed the input number
)        % Use as logical index to select the corresponding matches
1)       % Select the first match. Implicitly display

PowerShell v3+, 103 101 bytes
param($a,$n)for(;$n[++$a]-match'\w'){}$i=$a--;for(;$n[--$a]-match'\w'-and$a-ge0){}-join$n[++$a..--$i]

Kind of a goofy solution, but a different approach than others.
Takes input $a as the 0-based index of the string $n. Then, we find the boundaries of our word. While we've not reached the end of the string and/or we're still matching word-characters, we ++$a. Then, because of fenceposting, we set $i=$a--. Next, we crawl backwards, decrementing $a until it's either 0 or we hit a non-word-character. We then slice the input string based on those two demarcations (with some increment/decrements to account for OBOE), and -join it together to produce the result.
Examples
PS C:\Tools\Scripts\golfing> .\select-the-word-around-the-index.ps1 2 'This!test'
This

PS C:\Tools\Scripts\golfing> .\select-the-word-around-the-index.ps1 5 'This!test'
test

select-the-word-around-the-index.ps1

PHP, 98 bytes
function f($s,$p){foreach(preg_split('#\W+#',$s,-1,4)as$m)if($m[1]+strlen($m[0])>=$p)return$m[0];}

splits the string by non-word-characters, remembering their position (4 == PREG_SPLIT_OFFSET_CAPTURE), loops through the words until position is reached.
PHP strings are 0-indexed, cursor before character, but may be before or after the word

Python 3, 112 140 bytes
from string import*
p='_'+printable[:62]
def f(s,h,r=''):
 while s[h]in p and h>-1:h-=1
 while h+1<len(s)and s[h]in p:h+=1;r+=s[h]
 return r

0-indexed.
Seeks backward to the first alphanumeric character from the index, then goes forward to the last alphanumeric character after the index. There's probably a smarter way to do this.
Try it

@LeakyNun _ was added, I'm not sure why I'd get an error for f('abc',1) though.

Javascript (using external library) (168 bytes)
(n,w)=> _.From(w).Select((x,i)=>({i:i,x:x})).Split((i,v)=>v.x==" ").Where(a=>a.Min(i=>i.i)<=n-1&&a.Max(i=>i.i)>=n-2).First().Select(i=>i.x).Write("").match(/^\w*^\w*/)[0]

Link to lib:https://github.com/mvegh1/Enumerable/blob/master/linq.js
Explanation of code: Library accepts a string, which gets parsed into a char array. It gets mapped to an object storing the index and the char. The sequence is split into subsequences at every occurrence of " ". The subsequences are filtered by checking if the cursor index is contained within the min and max index of the subsequence. Then we take the first subsequence. Then we transform back to just a char array. Then we concatenate all characters with "" as the delimiter. Then we validate against word regex. Then we take the first match.

The word "word" is defined by the regex (?<!\w)\w+(?!\w), where \w is defined by [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_], or "alphanumeric characters in ASCII including underscore".

When I run that regex against ab!cd on regex101.com I get this: No match groups were extracted.
This means that your pattern matches but there were no (capturing (groups)) in it that matched anything in the subject string.
Maybe I'm making a mistake somewhere...

Why would I need to capture anything?

I know this isnt the place to learn, but I'm saying that when I run that regex against ab!cd I don't get anything. So why would 'ab' be the correct output?

https://regex101.com/r/sC5oY0/1

You are invited to our chatroom to further discuss your answer.

Perl 5 -p, 35 bytes
$b=<>;($_)=/.{$b}\w+/g;($_)=/\w+$/g

Try it online!

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/