Rajasekhar
Rajasekhar

Reputation: 2455

How to fetch Alphanumeric or numeric value in a string using Regex?

I would like to fetch one item in the string,

the main string is : This is an inactive AAA product. It will be replaced by replacement AAAA/BBBB number ABX16059636/903213712 during quoting

I would like fetch ABX16059636/903213712, is there any way to achieve this one using Regex ?

Pls share some suggestions pls.

Upvotes: 1

Views: 157

Answers (4)

Johan Walles
Johan Walles

Reputation: 1516

  1. I went to https://regex101.com/r/ARkGkz/1
  2. I wrote a regexp for you
  3. I used their code generator to produce Javascript code
  4. I then modded the Javascript code to only access the single match that you're after

This is the result:

const regex = /number ([^ ]+) /;
const str = `This is an inactive AAA product. It will be replaced by 
replacement AAAA/BBBB number ABX16059636/903213712 during quoting`;
let m;

if ((m = regex.exec(str)) !== null) {
    let match = m[1];
    console.log(`Found match: ${match}`);
}

The regex itself can be read as:

  1. First match number
  2. The parentheses contains the part we want to capture
  3. [^ ] means "Anything except for space characters"
  4. + means "One or more of these"
  5. Then at the end, we match a trailing space

Do use https://regex101.com/r/ARkGkz/1 and experiment with this.

Upvotes: 0

Ataur Rahman Munna
Ataur Rahman Munna

Reputation: 3917

Try the code below.It will show your matches as well as matches group.

const regex = /[A-Z]+[0-9]+\/+[0-9]+/g;
const str = `This is an inactive AAA product. It will be replaced by replacement AAAA/BBBB number ABX16059636/903213712 during quoting`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Live Demo

Upvotes: 1

Ravi Chandra
Ravi Chandra

Reputation: 687

var s = 'This is an inactive AAA product. It will be replaced by replacement AAAA/BBBB number ABX16059636/903213712 during quoting'
var pat = /[A-Z]{3}\d+\/\d+/i
pat.exec(s)

This regular expression matches any 3 alphabets followed by one ore more digits followed by / and then one or more digits.

Upvotes: 1

Abhishek Gurjar
Abhishek Gurjar

Reputation: 7476

Try with below regex,

var string = "This is an inactive AAA product. It will be replaced by replacement AAAA/BBBB number ABX16059636/903213712 during quoting"

var result = string.match(/[A-Z]+[0-9]+\/[0-9]+/g)

console.log(result)

Upvotes: 2

Related Questions