Navigating through the text in between search restrictions of lookbehind and lookahead can be

Below is the text I am working with.

Hello my name is Adam (age: 25) I live in US.

Hello my name is Bill (age: 23) I live in Asia.

I am trying to extract the age and location using lookahead and lookbehind.

The desired output format should be as follows.

["25, US", "23, Asia"]

This is how much progress I have made so far.

(?<=age: ).*?(?=$)

When using the JavaScript match function, I am getting this array.

["25) I live in US.", "23) I live in Asia."]

I tried replacing .*? with [0-9a-zA-Z] but it doesn't seem to be effective.

Answer №1

Perhaps,

.*\bage:\s*(\d+)\s*\) I reside in (.+)\.

might be a bit closer, with two capturing groups containing your desired strings.

Test

const regex = /.*\bage:\s*(\d+)\s*\) I reside in (.+)\./gm;
const str = `Hello my name is Adam (age: 25) I reside in US.
Hello my name is Bill (age: 23) I reside in Asia.`;
const subst = `$1, $2`;

const result = str.replace(regex, subst);

console.log(result);


If you want to simplify/update/experiment with the expression, it has been detailed on the top right panel of regex101.com. You can observe the matching steps or make changes in this debugger link, if you're interested. The debugger illustrates how a RegEx engine would sequentially process some sample input strings for matching.


RegEx Circuit

jex.im visualizes regular expressions:

https://i.sstatic.net/MdZJq.png

Answer №2

The request for your query was to use lookbehind and lookahead in the regex. However, in this scenario, utilizing them is not really necessary since it has been noted that some browsers may not support lookbehind. But just to showcase how it would appear, I have provided it below:

/^.*?(?<=age: )(\d+).*?(?<=I live in )([^.]+)(?=\.$).*?$/gm
  1. ^ denotes the start of the line.
  2. .*? finds the minimum match of 0 or more characters until:
  3. (?<=age: )(\d+) locates 1 or more digits that are preceded by 'age: ' (you can adjust this to (?<=age: +) to allow multiple spaces before the number).
  4. .*? seeks the minimal match of 0 or more characters until:
  5. (?<=I live in )([^.]+)(?=\.$) matches 1 or more non-period characters that come after the string 'I live in ' and before a period at the end of the line.
  6. .*?$ encompasses the remaining characters until the end of the line (which will just be a period).

let s = `Hello my name is Adam (age: 25) I live in US.

Hello my name is Bill (age: 23) I live in Asia.`;

let regex = /^.*?(?<=age: )(\d+).*?(?<=I live in )([^.]+)(?=\.$).*?$/gm;
let result = s.replace(regex, `$1, $2`);
console.log(result);

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

The callback keeps getting triggered repeatedly, and I'm struggling to understand the reason behind it

One of the challenges I am facing revolves around a utility function responsible for launching a child process. The goal is to halt the listening process and trigger the callback as soon as the child process outputs a specific message to stdout: export co ...

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

Filter a two-dimensional array based on the presence of a string value found in the second array

My logic for this assignment is not very good, as I need to filter a 2D array based on the values of another array. Let me provide an example of the 2-Dimensional Array: const roles = [ ['roles', 'admin', 'write'], ['ro ...

Choosing2 - incorporate a style to a distinct choice

Let's talk about a select element I have: <select id="mySelect"> <option>Volvo</option> <option value="Cat" class="red">Cat</option> <option value="Dog" class="r ...

Utilizing model associations in Sails.js to populate an array

I am currently using "sails": "~0.10.0-rc5", "sails-mongo": "^0.10.0-rc3". I have two models: Invoice and Item. Invoice model Invoice: { name: 'sample 1', items: [1,2] // 1,2 are the ids of the Item model } Item model Item { id: 1 ...

Introducing additional choices to the list and automatically refreshing the list with the latest updates

I am currently honing my skills in Yii2 by working on a project using this framework. One of the challenges I am facing is adding new list options dynamically without having to navigate away from the current page. When I click the "Add new option" button ...

Having troubles with delayed state changes due to setState being used within useEffect

I have been working on a slider effect using React Hooks and Redux, and here is the code I am using: const Barchart = ({chartData}) => { let newArray = [] let len = chartData.length const [XArray,setXArray]=useState([chartData]) const [ ...

Please ensure that the table is empty before reloading data into it

I am facing an issue while binding data from the database. The data is being bound every 5 seconds, however, it does not clear the previous data and keeps accumulating. Instead of displaying just 3 rows when there are 3 in the database, it adds 3 rows ev ...

Mastering the Art of Disabling buttons in Vue Based on Conditions

In my current project, I'm attempting to compare specific values of an initial object with an updated object in order to disable a button if they are the same. However, despite making changes, the button remains disabled: setDisabled() { return th ...

What is the process for generating an HTML document from start to finish with the 'html-element' node module?

Here is an example that demonstrates a flawed method: const HTML = require('html-element'); const doc = `<body> </body>`; const page = HTML.document.createElement(doc) page.appendChild('<div>1</div>') page.append ...

Node replication including a drop-down menu

Is there a way to clone a dropdown menu and text box with their values, then append them to the next line when clicking a button? Check out my HTML code snippet: <div class="container"> <div class="mynode"> <span class=& ...

I am in the process of transforming my basic JS Array into one that contains key/value

Currently, I am utilizing jQuery to create an Array in the following manner: var arr = new Array(); $('#some-form .some-input').each(function() { arr.push($(this).val()); ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...

Pass the JSON object to a separate .js file in react-native without using class declarations

I am currently working on a mobile app that utilizes the fetch API to make GET calls. I've encountered an issue where I'm trying to export a JSON object fetched from the server using the fetch method to another .js file in order to use it as an a ...

Is there a way to trigger an ajax call specifically on the textarea that has been expanded through jQuery?

Whenever I expand a textarea from three textareas, all three trigger an ajax call. Is there a way to only call the ajax for the specific expanded textarea? I tried using $(this).closest('textarea').attr('id'), but it didn't work. A ...

Not defined within a function containing arrays from a separate file

Can anyone help me with listing multiple arrays from another file? When I try to iterate through each array using a "for" loop, the code compiles and lists everything but gives an undefined error at the end. How can I fix this? I have included some images ...

What is the best way to bind a click handler or any event handler to my object or module?

Can someone help me with attaching event handlers to my module in a way that I am not sure how to achieve? Here is the snippet of my module: var globalModule = { name:'Banana on princess bed', init:function(){ alert('Init ...

JQGrid is a unique event grid that triggers only once for the inaugural loading, allowing users to apply a default filter upon first loading

I am currently using JQGrid (jQuery jQgrid not Gurrido) version 4.6.0 and I am in need of an event that occurs only once the grid has completed loading for the first time. I have attempted to use loadComplete and gridComplete, but it seems they both perfor ...

JavaScript: What is the concept of overriding function named params?

function retrieveData({item1 = "blue", item2 = 7}) { console.log('theItems'); console.log(item1); console.log(item2); } retrieveData( { item1: 'pink', item2: 9 } ); I've come across conflicting i ...

What is the solution for the error message: "[Vue warn]: Error in mounted hook: 'TypeError: document.getElementById(...) is null'" that appears in the <Root> component?

I'm facing an issue with a checkbox in my Vue.js application. Whenever the user checks this checkbox, the data property accepted changes from false to true. My goal is to hide certain HTML elements when accepted = true. I have been attempting to achi ...