Mickey Gray
Mickey Gray

Reputation: 460

Regex for first number after a number and period

I have an ordered list with names and addresses that is structured like:

1. Last, First  123 Main St  buncha 
    buncha buncha

2. Lasta, Firsta 234 Lane St etc etc

So I need a regex that finds the number that immediately follows the number with a period. So in this case an array containing [123, 234]. I have a couple of patterns I've tried. The one that I think is the closest is

/(?![0-9]+\.)[0-9]+/gim; 

unfortunately this just returns every number, but i think its in the right area. Any help would be appreciated.

Upvotes: 1

Views: 448

Answers (3)

The fourth bird
The fourth bird

Reputation: 163362

You could also use a capturing group

^\d+\.\D*(\d+)

Explanation

  • ^ Start of string
  • \d+\. Match 1+ digits and .
  • \D* Match 0+ any char except a digit
  • (\d+) Capture group 1, match 1+ digits

Regex demo

const regex = /^\d+\.\D*(\d+)/gm;
const str = `1. Last, First  123 Main St  buncha
    buncha buncha

2. Lasta, Firsta 234 Lane St etc etc`;

let res = Array.from(str.matchAll(regex), m => m[1]);
console.log(res);

Upvotes: 0

Barmar
Barmar

Reputation: 781058

Use a positive lookbehind to explicitly match the number, period, and the text between that and the number in the address.

const string = `1. Last, First  123 Main St  buncha 
    buncha buncha

2. Lasta, Firsta 234 Lane St etc etc`;

let regex = /(?<=^\d+\.\D*)\d+/gm;

console.log(string.match(regex));

Upvotes: 1

renich
renich

Reputation: 146

Something like this

const source = 
`1. Last, First  123 Main St  buncha 
    buncha buncha

2. Lasta, Firsta 234 Lane St etc etc`;

const result = source.match(/(?<=(\d+\..+))\d+/gm);
console.log(result);

Upvotes: 1

Related Questions