73892

Regex for a valid hashtag

<h3>Question</h3>

I need regular expression for validating a hashtag. Each hashtag should starts with hashtag("#").

Valid inputs:

1. #hashtag_abc

2. #simpleHashtag

3. #hashtag123

Invalid inputs:

1. #hashtag#

2. #hashtag@hashtag

I have been trying with this regex /#[a-zA-z0-9]/ but it is accepting invalid inputs also.

Any suggestions for how to do it?


<h3>Answer1:</h3>

There are 2 issues:

<ul><li>[A-z] allows more than just letter chars ([, \, ], ^, _, ` )</li> <li>There is no quantifier after the character class and it only matches 1 char</li> </ul>

You might also need anchors (^ / $) if you want to have a full string match.

Use

/^#\w+$/

See the regex demo.


<h3>Answer2:</h3>

The current accepted answer fails in a few places:

<ul><li>It accepts hashtags that have no letters in them (i.e. "#11111", "#___" both pass).</li> <li>It will exclude hashtags that are separated by spaces ("hey there #friend" fails to match "#friend").</li> <li>It doesn't allow you to place a min/max length on the hashtag.</li> <li>It doesn't offer a lot of flexibility if you decide to add other symbols/characters to your valid input list.</li> </ul>

Try the following regex:

/(^|\B)#(?![0-9_]+\b)([a-zA-Z0-9_]{1,30})(\b|\r)/g

It'll close up the above edge cases, and furthermore:

<ul><li>You can change {1,30} to your desired min/max</li> <li>You can add other symbols to the [0-9_] and [a-zA-Z0-9_] blocks if you wish to later</li> </ul>

Here's a link to the demo.

来源:https://stackoverflow.com/questions/42065872/regex-for-a-valid-hashtag

Recommend

  • Only add header on proxied API Gateway request with Lambda authorizer
  • No package msyql-server available
  • F# List of Union Types
  • How to find “Docker Host URI” to be used in Jenkins “Docker Plugin”?
  • Error when “import matplotlib.pyplot as plt”
  • R: use min() within dplyr::mutate()
  • Ways to determine returning “anonymous” guests in PHP
  • Passing a list of parameters into a Python function [duplicate]
  • Saved Core Data does not persist after app closes 80% of the time
  • CSS button not styling
  • Activate UISearchBar when the controller is loaded
  • org.springframework.security.oauth2.common.exceptions.InvalidGrantException: Bad credentials
  • Encoding/decoding PDP-11 assembly language to binary and hex?
  • Cannot retrieve CustomAttributes in Interceptor using DynamicProxy
  • Create my own classList object when the browser does not implement it itself
  • Extract Data from a Web Page - using VBA
  • How do I force ASP.NET Ajax to use a script from the FS and not WebResource.axd, or to reduce its HT
  • Why is this Animatable property being set again?
  • Limit # of records returned based on a form control
  • Migrating MOSS 2007 from SQL 2000 to SQL 2005 [closed]
  • Connect from a client to a sails based server
  • NoSuchMethodError javax.ws.rs.core.Application.getProperties()Ljava/util/Map
  • how can i close the resultSet, prepareStatement, conn in several methods below to avoid rs close and
  • Adding custom message on Thank You page by shipping method
  • How exactly do you use json_decode to pass a javascript array to php?
  • date changes on export kendoGrid
  • Expression.Call GroupBy then Select and Count()?
  • How to process remote XML files with XSLT
  • Ajax call on Multiple selection in Select box
  • how to run a different select statement based on condition in Hive SQL
  • Typeahead.js does give me suggestions but doesn't select them
  • how to get the location(lat/lng) on google maps v3 from the location(x,y)
  • Send array to next viewcontroller iOs xcode [duplicate]
  • Codeigniniter insert data through models and controller
  • Cross compile glibc for arm, got undefined reference to some unwind functions
  • WPF custom control and direct content support
  • PHP Permalinks.. how to change?
  • What does the “id” field in an Android “Google Play Music” broadcast intent correspond to?