Regular expression to match only alphanumeric characters without any numbers at the start or end

Creating a regex pattern that only matches letters and numbers, not allowing numbers at the beginning or end:

  • johnDoe123 is acceptable
  • 4janeDoe is not acceptable
  • johndoe5 is not acceptable
  • john_doe is not acceptable

Attempted solution:

[a-z0-9_]

Unfortunately, it did not produce the desired results.

Answer №1

If you are looking to match a single character as well:

 ^[a-z](?![a-z\d]*\d$)[a-z\d]*$

Explanation

  • ^ Represents the start of the string
  • [a-z] Matches a single character from a-z
  • (?![a-z\d]*\d$) Negative lookahead ensuring that the string does not end with a digit
  • [a-z\d]* Matches optional characters from a-z or digits
  • $ Denotes the end of the string

Take a look at the regex demo.

If your regex engine supports lookbehind assertions, you can use this pattern:

^[a-z][a-z\d]*$(?<!\d)

Explanation

  • ^ Indicates the beginning of the string
  • [a-z] Matches a single character from a-z
  • [a-z\d]* Matches optional characters from a-z or digits
  • $ Denotes the end of the string
  • (?<!\d) Negative lookbehind asserting that there is no digit at the end of the string

Check out another example on regex101.

Answer №2

Here's a functioning example ^[a-z][a-z\d]*[a-z]$

const pattern = /^[a-z][a-z\d]*[a-z]$/
const words = ['hello123', '123hello', 'hello_world']
words.forEach(check)

function check(word) {
  console.log(word, word.match(pattern) ? 'match' : 'no match')
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to generate a new column in pandas by calculating the variance between two string columns?

Is there a way to add a new column in pandas that shows the difference between two existing columns containing strings? For example, I have a "Good Address" column with entries like "123 Fake Street Apt 101" and a "Bad Address" column with entrie ...

When the mouse hovers over, include a fade-in effect for the image

I am working with two overlapping images and have successfully implemented a function to display the second image on mouse hover. However, I am struggling to incorporate a CSS transition property for a smoother image transition effect. Currently, when the ...

Issue with showing multiple images on HTML page

I'm currently working on enhancing my webpage by enabling the upload of multiple images. However, I'm facing challenges in figuring out how to obtain a valid URL for the image source and to verify if the correct number of files have been uploaded ...

display content in the text area upon clicking a link

I currently have two HTML text areas, each with their own unique ID: textarea1 and textarea2. Below is a list of fruits: Orange Apple The functionality I am looking for is as follows: when the user clicks on "Orange" while focusing on textarea1, the te ...

Which is Better: Parsing Django Models on the Server Side or Client Side?

What is considered the most effective practice for displaying model objects on the client side while working on Django app development? Is it recommended to parse the models using server-side code or is it better to utilize client-side templating languages ...

Having difficulty attaching events to Bootstrap 3 button radios in button.js

Struggling with extracting the correct value from a segmented control created using the radio button component of button.js in Twitter Bootstrap 3. Upon binding a click event to the segmented control and running $.serialize() on its parent form, I noticed ...

Tally the quantity of data points within jQuery Datatables

Upon navigating to my jQuery DataTable, I aim to showcase the count of Users pending activation. Typically, I would use fnGetData with (this), but since I am not triggering this on a click event and wish to count all entries in the table, I am unsure of ho ...

Steps to insert a large image into a div while maintaining the size ratio

https://i.sstatic.net/WvBbF.png I'm struggling to add a logo to the right corner of this div The logo size is too big and it doesn't adjust properly to the existing div height and width Below is the code I've tried, but the image is ruini ...

Maintain user authentication in Firebase as long as the localStorage object remains active

I am currently working on an app using Ionic, Angular2, and Firebase. My approach involves saving the auth.currentUser information in the localStorage when a user logs in or registers. However, I recently discovered that having the user variable set in th ...

Incorporate HTML into FormControlLabel with Material UI

In the project I am working on, there is a need to customize a checkbox using FormControlLabel. The requirement is to display the name and code of an item one above another with a reduced font size. Attempts were made to add HTML markup to the label or use ...

The API results are able to be displayed in the console, but unfortunately cannot be shown on the user interface. Any efforts to map the results will result in an Un

Can anyone help me troubleshoot an issue with displaying information from a free API on my page? I'm developing a cryptocurrency app using React, and while I can see the array data with console.log(response.data), I encounter an error when I try to se ...

Mastering the art of utilizing callbacks in AngularJS for consuming an API

Having trouble handling data from an API and structuring it effectively before passing it to the controller. I've created a factory that retrieves user data from the API, but the provideAllUserData function is causing issues. Below is my services.js: ...

Implementing Google Calendar access token in JavaScript: A practical guide

I have a question about Google Calendar and I'm hoping you can assist me. I currently have an access_token from Google Calendar that has been stored in the localStorage. const googleAccessToken = e.vc.access_token; localStorage.s ...

What are the best ways to resolve the warning from webpack in Express?

I have set up webpack to bundle both the server and client side code... Below is my webpack configuration: const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin&a ...

Position a div in the center of a section

Having trouble centering a <div> within a <section>? I've tried setting margin-left and margin-right to auto without success. Any other suggestions? Check out the jsFiddle illustrating the issue: http://jsfiddle.net/veWKh/ ...

The function this.$set is failing to update an array in VueJS

I am facing an issue where the console log shows me the updated array xyz, but when I try to print it in the DOM using {{xyz}}, it does not update. Can anyone shed some light on why this might be happening? data() { return { xyz: [] } }, met ...

Instructions for user to upload and play an MP4 file on their PC

For my web project that utilizes node.js, HTML, and JavaScript, I am looking to incorporate a video player element. I want users to have the ability to click a button and play an MP4 file directly on the webpage. How can I achieve this? I currently have s ...

In Python, replace every instance

Hey there, I've encountered an issue with my Python script. I'm attempting to use re.sub to substitute a variable within the code. When the variable occurs only once, everything works perfectly fine. However, I run into an error when it occurs tw ...

What is the best way to use a Handlebars file on multiple routes?

I have been working on extracting articles from a news website by scraping them successfully. The data is being displayed properly on the front-end console log, but I am facing an issue with rendering it onto the page using a button - it only appears when ...

Accordion-inspired animation implemented on an Angular component using a selection of different templates

Currently, I am developing a production app with a card-style layout. All filters (such as date pickers) and visualizers (like tables and charts) are enclosed within a "Card" component. Additionally, there are two child components that inherit from this cl ...