Finding patterns of different lengths with JavaScript Regular Expressions

Allow me to clarify my question with an illustration:

I am extracting page names from a website. The page names vary in length, for example:

  1. Data1|Data2|Data3
  2. Data1|Data2|Data3|Data4
  3. Data1|Data2

I need to create a Regex that will work for all of the scenarios above. Another user previously shared the following:

 /(.*?)\|(.*?)\|(.*?)\|(.*)/gm;

This Regex pattern works well when there are always four groups separated by "|" and empty spaces between them. However, it fails if there are only two values. Can anyone provide guidance on how to modify this regex to handle different numbers of groups?

Answer №1

Unclear on your previous message, but here is some assistance. The code below only allows for alphanumeric characters and spaces:

/([a-zA-Z 0-9]{1,}\|){1,}[a-zA-Z 0-9]{1,}/g

Answer №2

This code will require a minimum of two data fields and a maximum of four fields.

/(?:([^|]*)\|){1,3}([^|]*)/gm;

To allow only one field (without the pipe):

/(?:([^|]*)\|){,3}([^|]*)/gm;

The {n,m} in the pattern means that it is allowed to repeat between n and m times.

An important thing to note is that instead of using .*?, [^|]* is used to match anything except the pipe character |. Also, non-matching groups (?:) are utilized so that the groups containing pipes are not visible, enabling you to extract the fields as they were before.

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 process for converting Database/Table Data into a File Name?

Hey there! I have a query regarding Leaflet Markers that I need help with. So, I have this database table with a field named icon_name which contains values like: |icon_name| ___________ |FIRE | |HOMICIDE | |RAINSTORM| Additionally, I have a folder ...

Unleashing the potential of extracting the value of a subsequent iteration while within the

Currently, I am facing a dilemma as I am unable to comprehend the logic required to design this algorithm. The problem at hand involves a sequence of images with arrows placed alternatively between each image. The structure appears as follows: Image -> ...

Issue with v-model not updating data correctly when using switch and select dropdown in VueJS

I am developing a dynamic admin panel that includes a CRUD generator using Laravel and Vue. Within my table, I am asynchronously loading data from an API. One specific column in the table, called is_featured, needs to function as a switch. This will allow ...

What steps can I take to rearrange my return statement within an asynchronous function?

Imagine having a function that fetches data from a database. findById(id) { return Model.findById(id) } The goal is to rearrange the output from the user data in this format: { name: "Tom", age: 57 } To something like this: { message: ...

Adding an icon to indicate that the last reading date is over 24 hours old - how to do it!

Within my HTML, I have the following code snippet: {{hsParametersLastRead.readingDate | date:'medium'}} In my controller, I am using this code: $http.get(hsParametersLastReadEndpoint).success(function (hsParametersLastRead) { $ ...

Steps for adding an npm dependency as a peer dependency:

Is there a way in npm to install dependencies as peer-dependencies similar to the yarn option --yarn, rather than manually adding them? For instance: "peerDependencies": { "@angular/core": "^7.0.0" } Update: Further clarifi ...

Assign a value to a hash object based on a specific location stored within an array

I'm struggling to figure out how to retrieve the original JSON data when its structure is variable. var jsonData = { "parent": { "child": "foo" } }; fu ...

What is the reason for an event triggering on a parent element before its child element when using a descendant selector?

I encountered a strange issue in my code where the event on a parent element seemed to trigger before the event on its child, rendering my e.stopPropagation() ineffective. Demo: $(document).ready(function() { // Directly binding events to the elemen ...

Exploring the Process of Obtaining _Value Properties within Vue 3 Ref

Hello, I've been attempting to access the values from the _value property in Vue without success. How can I retrieve these values such as accessKey, align, ariaAtomic, etc.? Specifically, I am interested in getting the value of clientWidth. https://i ...

How can you prevent "hits" from being displayed on the screen until the searchBox is utilized in React InstantSearch?

I am currently implementing React InstantSearch in Algolia and I am trying to configure it to hide the "hits" component by default, only displaying it when the searchBox is clicked. My initial research led me here: Although I was able to implement the qu ...

Personalize the 'Standard', 'Fresh', and 'Modify' aspx widget devoid of Share Point or Infopath integration

As I work on developing a Sharepoint 2010 page to meet my team's needs, I am faced with restrictions on using Sharepoint Designer and InfoPath. This means I am unable to customize the default form for adding, editing, or viewing items on my individual ...

React.js: Oops! Looks like we hit a snag - the call stack size has been exceeded

Is React.js using props to send values to descendant components wrong? const Child = props => <div onClick={ e => console.log(props.value) }>Click to see value.</div> const Father = props => <div>{ React.cloneElement(props.child ...

The issue with THREE.js ORBITCONTROLLS not responding to changes in mouse button settings is causing inconvenience

Hey there, currently working on a project using THREE.js and I've run into an issue with my .mouseButtons functionality. var controls = new THREE.OrbitControls( camera, renderer.domElement ); controls.target.set( 0, 25, 0 ); c ...

Display input field in AngularJS when radio button is selected

My JavaScript array looks like this: $scope.quantityMachines = [ { 'snippet' : 'One' }, { 'snippet' : 'Two' }, { 'snippet' : 'Three or more', 'extraField' : true }, { ' ...

What is the best way to convert base64 into an image using Node.js?

I'm having trouble with decoding an image sent as base64 through sockets. The file that should contain the image is being written as a base64 string instead of a jpg file. For encoding through socket: function encode_base64(filename) { fs.readFile( ...

Dynamic anime-js hover animation flickering at high speeds

I have implemented the anime-js animation library to create an effect where a div grows when hovered over and shrinks when moving the mouse away. You can find the documentation for this library here: The animation works perfectly if you move slowly, allow ...

Error encountered in Selenium Webdriver: Element is not currently in view

I encountered an issue when trying to click on a button using the same type of code that worked fine for selecting a drop down. The error message I received was "Element is not currently visible and so may not be interacted with". Command duration or timeo ...

Ways to retrieve a service variable within a delegated function (callback)

I am currently using a service that has a variable which needs to be updated by the service itself. However, I am facing an issue where I cannot access the variable in anonymous or delegated functions. (function() { 'use strict'; angular ...

What is the reason behind having to refresh my ReactJS page despite it being built with ReactJS?

I have developed a task management application where users can input notes that should automatically update the list below. However, I am facing an issue where the main home page does not display the updated todos from the database unless I manually refres ...

When dynamically accessed, the property of a JSON object is considered "undefined"

I'm running into trouble trying to access properties of a JSON object in my JavaScript code using obj[varWithPropName]. Strangely, it does work when I use obj["PropName"]. Here's a simplified snippet for reference: import * as CharInfo from &ap ...