Check if a string contains only special characters and no letters within them using regular expressions

My goal is to validate a string to ensure it contains letters only between two '#' symbols.

For example:

#one# + #two# - is considered a valid string

#one# two - is not valid

#one# + half + #two# - is also not a valid string (only #one# and #two# are valid sections)

The rule is that odd occurrences of '#' allow for entering letters, while even occurrences of '#' should close the space where letters can be written.

I have created a regex pattern that works for most cases, but I'm struggling with the last scenario.

Here is my current regex pattern:

/^[^a-zA-Z]*(#.+#)[^a-zA-Z]*$/g

I'm testing this pattern on the regex testing site

As a last resort, if regex is not sufficient, I may consider splitting the string on '#' and checking the remaining sections for letters in typescript.

Any thoughts on how to successfully validate this type of string? Thank you.

Answer №1

One approach is to utilize an alternation to match the entire string, either not containing a character a-z, a newline, or a #, OR matching the pattern #[a-zA-Z]+# where only characters a-z can be present in between

^(?:[^a-zA-Z\r\n#]|#[a-zA-Z]+#)+$
  • ^ Denotes the start of the string
  • (?: Represents a non-capturing group
    • [^a-zA-Z#\r\n] Matches any character except those listed
    • | Or
    • #[a-zA-Z]+# Matches #, 1 or more characters a-zA-Z, and #
  • )+ Closes the non-capturing group (with the alternation) and repeats it 1 or more times to avoid matching an empty string
  • $ Indicates the end of the string

Check out the Regex demo here


To also match odd occurrences, you could modify the regex like this

[^a-zA-Z\r\n#]|#[a-zA-Z]+#(?:[a-zA-Z]+#)*)+$

See the Regex demo for this variation

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

Incorporate matTooltip dynamically into text for targeted keywords

I'm currently tackling a challenge in my personal Angular project that utilizes Angular Material. I'm struggling to find a solution for the following issue: For instance, I have a lengthy text passage like this: When you take the Dodge action, ...

Execute the unknown function parameter

Trying to figure out how to convert an argument into an anonymous function, but struggling to find clear instructions. I know how to cast on variable assignment, but unsure if it's possible and how. Working with lodash where the typings specify the a ...

What steps should I take to resolve the issue of 'unable to locate the name 'OktaAuthService' error?

I am currently trying to incorporate authentication into an Angular application using Okta. I have carefully followed the step-by-step instructions provided in the documentation at this link: . However, I am encountering an error when attempting to start t ...

Angular2 and ReactiveX: Innovative Pagination Strategies

Currently, I am diving into the world of ReactiveX. To make things easier to understand, I have removed error checking, logging, and other unnecessary bits. One of my services returns a collection of objects in JSON format: getPanels() { return this. ...

Unable to retrieve values using any = {} in TypeScript Angular 8

import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { enableProdMode } from '@angular/core'; enableProdMode(); @Component({ selector: 'app-home', templat ...

What is the procedure to authenticate a specific row within a table using the ROBOT framework?

When adding a new device, I want to ensure that the second row in a table is validated using the ROBOT framework. For example, how can I validate a specific row in a table with the ROBOT framework? https://i.sstatic.net/Ovqp7.png Appreciate your help! ...

Utilizing TypeScript generic types as a key for an object

function createRecord<T extends string>(key: T): Record<T, string> { return { [key]: 'asdf' }; } Encountering an issue: The type '{ [x: string]: string; }' is not matching with the expected 'Record<T, st ...

The subscription function in observables may result in values that are undefined

I integrated a new angular 2 library into my application called "angular2-grid". This library is located within the node_modules folder. Furthermore, I created a service as shown below: import { Injectable } from '@angular/core'; import { Htt ...

Is there a way to customize the hover style of Material UI Select or Menu MenuItem using the theme?

The theme I designed import { createMuiTheme } from 'material-ui/styles'; export const MyTheme = createMuiTheme({ palette: { primary: { light: '#757ce8', main: '#3f50 ...

Integrating TypeScript into an established project utilizing React, Webpack, and Babel

Currently, I am in the process of integrating Typescript into my existing React, Webpack, and Babel project. I aim to include support for file extensions such as [.js, .ts, .tsx] as part of my gradual transition to Typescript. I have made some progress, b ...

Setting up a variable with no operation assigned to it

As I delved into the Angular utils source code, I stumbled upon this interesting line: export const NOOP: any = () => {}; It seems pretty straightforward - a variable that doesn't perform any operation. But then, within the same library, there is ...

Looking for assistance with creating a .NET regular expression specifically for parsing JSON data?

Currently, I am in the process of building a JSON parser for .NET that is effectively parsing JSON objects. However, I have hit a roadblock when it comes to parsing complex strings. For instance: The parser is able to successfully parse \"Hi there!&b ...

How to Retrieve an Array from a Promise Using Angular 4 and Typescript

I am encountering difficulties when trying to store data from a returned promise. To verify that the desired value has been returned, I log it in this manner: private fetchData() { this._movieFranchiseService.getHighestGrossingFilmFranchises() ...

Typescript - Keeping a log of object keys along with their corresponding key type values

Imagine having the following scenario where you need to create an object with keys that are transformed versions of the original type's values: export type CCDTypes = { AuthorisationCaseEvent: AuthorisationCaseEvent, AuthorisationCaseField: Author ...

Encountering an "Unexpected token" error when importing a JSON file in TypeScript even though the JSON is valid

I recently read an article on Hacker Noon about importing JSON into TypeScript, and decided to give it a try in my code. Here's the import line I used: import data from './assets/fonts/helvetiker_bold.typeface.json'; To test if the import ...

Is it more efficient to define a variable or call a method from an object?

Which approach is more effective and why? Option 1: Declaring a variable exampleFunction(requestData: Object) { const username = requestData.username; doSomething(username); } Option 2: Accessing the object property directly exampleFunction(reques ...

Find all documents in Angular Firestore that are related to a specific document_REFERENCE

Seeking a way to search through all documents in collection a that have a reference to a specific document in collection b. Despite my efforts, I couldn't find a solution here or on Google :/ This is what I tried in my service class: getAsFromB(id ...

Discovering the current page using ons-navigator in Onsen UI

I am currently attempting to determine the page I am on while using the popPage() function with Onsen UI's ons-navigator. I have tried the following methods, but they always return false regardless: this.navigator.nativeElement.popPage().then((page: a ...

The search for d.ts declaration files in the project by 'typeRoots' fails

// Within tsconfig.json under "compilerOptions" "typeRoots": ["./@types", "./node_modules/@types"], // Define custom types for Express Request in {projectRoot}/@types/express/index.d.ts declare global { namespace Express { interface Request { ...

An issue has occurred: the property 'map' cannot be read as it is undefined

Encountered this unexpected error and struggling to understand the reason behind it.. I've been attempting to showcase events on angular-calendar: Error occurred in error_handler.ts:1 - ERROR TypeError: Cannot read property 'map' of unde ...