Atlante Avila
Atlante Avila

Reputation: 1488

I need help getting the first n characters of a string up to when a number character starts

I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.

Not sure how to do this with regex my limited knowledge is blocking me at this point:

^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring

Upvotes: 1

Views: 481

Answers (5)

user557597
user557597

Reputation:

Since it's hard to tell what you are trying to match, I'd go with a general regex

^\d?\D+(?=\d)

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163217

Using \w will match a word character which includes characters and digits and an underscore.

You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z

^[0-9]?[A-Za-z]+

Regex demo

const regex = /^[0-9]?[A-Za-z]+/;
[
  "7EUSA8889er898",
  "somelongstring292894830982",
  "SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));

Upvotes: 4

xchrisbradley
xchrisbradley

Reputation: 493

There are answers to this but here is another way to do it.

var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';

var Extract = function (args) {
    var C = args.split(''); // Split string in array
    var NI = []; // Store indexes of all numbers
    // Loop through list -> if char is a number add its index
    C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
    // Get the items between the first and second occurence of a number
    return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));

Output

EUSA
SWFX7

Upvotes: 0

Jan Turoň
Jan Turoň

Reputation: 32912

If you want to create function where the RegExp is parametrized by n parameter, this would be

  function getStr(str,n) {
    var pattern = "\\d?\\w{0,"+n+"}";
    var reg = new RegExp(pattern);
    var result = reg.exec(str);
    if(result[0]) return result[0].substr(0,n);
  }

Upvotes: 0

Masoud
Masoud

Reputation: 342

Can use this regex code:

(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)

I try with exmaple and good worked:

1- somelongstring292894830982 -> somelongstring

2- 7sdfsdf5456 -> 7sdfsdf

3- 875werwer54556 -> 875werwer

Upvotes: 0

Related Questions