Uzi
Uzi

Reputation: 453

Javascript: Searching substring pattern and returning found string

I have a string composed by several fields. Two of which will always vary in length. I could simply use substring if all fields have fixed lengths.

Sample:

48001MCAbastillas2200800046300017100518110555130000123

The fields are divided like this:

480 | 01 | MCAbastillas | 2200800046300017 | 100518 | 110555 | 130000 | 123

The bolded fields are the fields that varies in length. They represent a name and a amount, respectively. I already posted this question but I mistakenly tagged it with Java. I tried to interpret the provided answers into Javascript but being no expert in it, I spent all day producing no results :(

Upvotes: 2

Views: 67

Answers (4)

Tigger
Tigger

Reputation: 9130

A more complex version that breaks all the parts based on known values. The regex answer is the way to go.

var r1 = "48001MCAbastillas2200800046300017100518110555130000123";
var r2 = "48001RANDOM220080004630001710051811055512345123";

function extract(str) {
    var i = 5,max = str.length;
    var parts = [], cut1, cut2 = (max - 3);
    for(;i<max;i++) {
        if (! isNaN(parseInt(str[i]))) {
            cut1 = i;
            break;
        }
    }
    parts.push(str.substr(0,3));
    parts.push(str.substr(3,2));
    parts.push(str.substr(5,(cut1 - 5)));
    parts.push(str.substr(cut1,16));
    parts.push(str.substr((cut1 + 16),6));
    parts.push(str.substr((cut1 + 16 + 6),6));
    parts.push(str.substr((cut1 + 16 + 12),(cut2 - (cut1 + 16 + 12))));
    parts.push(str.substr(cut2,3));      
    return parts;
}

console.log(extract(r1));
console.log(extract(r2));

Upvotes: 0

user10616833
user10616833

Reputation:

const test = [
  '48001MCAbastillas2200800046300017100518110555130000123',
  '48001MCAbasti2200800046300017100518110555130000123',
  '48001MCAbastillasXYZ2200800046300017100518110555130000123',
  '48001MCAbastillas2200800046300017100518110555130000999123',
  '48001MCAbastillas2200800046300017100518110555130123',
  '48001MCAbastillasXYZ2200800046300017100518110555130000999123',
  '48001MCAbasti220080004630001710051811055513123'
]

const p = /(?<name>\D+)(\d{28})(?<amount>\d+)(\d{3}$)/

console.log (test.map (s => s.match (p).groups))

Upvotes: 0

Apolo
Apolo

Reputation: 4050

var input = '48001MCAbastillas2200800046300017100518110555130000123';
// match parts with regex
var match = input.match(/^(.{3})(.{2})([a-zA-Z]+)(.{16})(.{6})(.{6})(\d+)(.{3})$/);
// remove first element (full matching input)
match.shift();
// build output
var output = match.join(' | ');
console.log(output);

Upvotes: 2

kakamg0
kakamg0

Reputation: 1096

You can use regular expression to capture the groups

const regex = /^(.{3})(.{2})(\D+)(.{16})(.{6})(.{6})(\d+)(.{3})$/
const str = '48001MCAbastillas2200800046300017100518110555130000123'
const values = str.match(regex)
console.log(values)

Upvotes: 4

Related Questions