Skip to main content
Marnida
Known Participant
January 23, 2021
Answered

RegEx for getting the first number before the first slash

  • January 23, 2021
  • 4 replies
  • 5813 views

Hello! I need a RegExp to get the first number before the first slash in a string. I've been banging my head against this for a while... and failing.

For the substring before the slash, I've got (^[^\/]+). And for the last number in that substring I've got... not much. I've been hitting it with combinations of $ and \d but nothing's working.

 

The strings will be formed like these;

 

- 1 / something / something else / ...

~ 2 / another something / something else / ... / ...

- 3-4 / thing / ...

-~ 5-6 / ... / ... / ... / ... / ...

In each case, I want the number imediately to the left of the first slash. So from the above examples I want 1, 2, 4 and 6 respectively.

 

Someday I'll understand RegEx... but not today, it seems. Please help!

 

This topic has been closed for replies.
Correct answer Inventsable

Hello, yet another different approach but figured I'd give some pure RegExp solutions. From the left:

 

function getLayerZoomNumber(text) {
    var matches = text.match(/[-~]\s(\d*)?-?(\d*)/);
    var match = matches[matches.length - 1]
    return match.length ? +match : +matches[matches.length - 2];
}

 

Reading from the right:

 

function getLayerZoomNumber(text) {
    var matches = text.match(/(\d{1,})\s\//);
    return +matches[matches.length - 1]
}

 

 When tested:

 

var texts = [
    "- 1 / something / something else / ...",
    "~ 2 / another something / something else / ... / ...",
    "- 3-43 / thing / ...",
    "-~ 5-666 / ... / ... / ... / ... / ..."
]
for (var i = 0; i < texts.length; i++) {
    var result = getLayerZoomNumber(texts[i])
    alert(result)
    // Returns 1, 2, 43, 666
}

 

Left here, and right here. Since capture groups are indexed withing a RegExp.match function, I know to automatically target the last capture group but for reading from left will always fallback to the one prior when that match has no character length. I wasn't sure if these strings you'd posted were simplified or if there's a chance that numbers or slashes would exist prior the dash/tilde syntax, in which case either of these should still work.

 

4 replies

pixxxelschubser
Community Expert
January 28, 2021

@Marnida 

do you have problems with the codes in all (correct) answers?

 

Or why don't you give any feedback?

Marnida
MarnidaAuthor
Known Participant
January 29, 2021

Hi there, my appologies, I've just been swamped. I carried on bashing at it and ended up with this, which isn't pretty but seems functional:

function getLayerZoomNumber( text ){
        var reg = new RegExp( (/^[^\/]+/) );
        var lyr = text.match( reg );
        var resMultiplier = 0;
        for( var i =0; i< lyr.length; i++ ){
                for(var j = 0; j< lyr[i].length; j++){
                        if ( !isNaN( lyr[i].charAt(j) )){
                                if( lyr[i][j] > resMultiplier ){
                                        resMultiplier = lyr[i].charAt(j);
                                }
                        }
                }
        } 
        return resMultiplier; //the largest number in the first part of the text
}

 

IMHO these strings are paths to files or folders.

These strings are paths representing the grouping hierarchy. Each group has its own identity in the context of a system map.

  1. Where the strings are comes from?

They're generated when the script recursively walks the DOM.

  1. Are there really spaces and tilde signs?

Yeah, that's a naming convention indicating what we're planning on doing with the content of the layer.

  1. Are numbers really only in the first part?

Numbers could be anywhere in the string, but the only one I'm interested in is the one imediately to the left of the first slash. I want to use it as a multiplier for the resolution of exported PNGs.

 

Many thanks for all the replies! I'm going to study the above anwers a bit more to get my head around them, and hopefully improve my code.

 

Inventsable
InventsableCorrect answer
Brainiac
January 30, 2021

Hello, yet another different approach but figured I'd give some pure RegExp solutions. From the left:

 

function getLayerZoomNumber(text) {
    var matches = text.match(/[-~]\s(\d*)?-?(\d*)/);
    var match = matches[matches.length - 1]
    return match.length ? +match : +matches[matches.length - 2];
}

 

Reading from the right:

 

function getLayerZoomNumber(text) {
    var matches = text.match(/(\d{1,})\s\//);
    return +matches[matches.length - 1]
}

 

 When tested:

 

var texts = [
    "- 1 / something / something else / ...",
    "~ 2 / another something / something else / ... / ...",
    "- 3-43 / thing / ...",
    "-~ 5-666 / ... / ... / ... / ... / ..."
]
for (var i = 0; i < texts.length; i++) {
    var result = getLayerZoomNumber(texts[i])
    alert(result)
    // Returns 1, 2, 43, 666
}

 

Left here, and right here. Since capture groups are indexed withing a RegExp.match function, I know to automatically target the last capture group but for reading from left will always fallback to the one prior when that match has no character length. I wasn't sure if these strings you'd posted were simplified or if there's a chance that numbers or slashes would exist prior the dash/tilde syntax, in which case either of these should still work.

 

pixxxelschubser
Community Expert
January 25, 2021

Hi together.

 

IMHO these strings are paths to files or folders.

  1. Where the strings are comes from?
  2. Are there really spaces and tilde signs?
  3. Are numbers really only in the first part?

 

I would go a different (safe) way.

First remove all the spaces and then get the first part till to the first slash --> Separate the first part and then isolate the numbers in front of the slash.

You can use a Regex like

 

 

var str = "- 3-44   / thing 1 / ...";
str = str.replace (/ /g, "");
var reg1 = RegExp("^[^\\/]+\\d*?(?= ?\\/)");
// check if the pattern exists
alert (reg1.test (str)) // result /*boolean*/ true

 

 

 

Or much more simple: split the string

 

 

var str = "- 3-44   / thing 1 / ...";
var str = str.replace (/ /g, "").split ("/"); // result: /*Array*/ -3-44,thing1,...

 

 

 

Now you can grab the "last" Number(s)

 

 

alert ("str.match: " +str[0].match (/\d+$/)) // result /*string*/ 44

 

 

 

Have fun

😉

CarlosCanto
Community Expert
January 23, 2021

you got it right @femkeblanco, it just needs a capture group to avoid using "toString()"

 

 

var str = "- 3-4 / thing / ...";

var regexp = /(\d) \//; // find a digit followed by a space followed by a slash. To save the digit also, enclose between parenthesis

var arr = str.match (regexp); // returns an array of matches, match[0] = digit-space-slash, match[1] = capture group, stuff between parenthesis

alert(arr[1]);
//$.writeln(arr[1]);

 

 

but lets see what a real regexp expert ( @pixxxelschubser  ) comes up with

m1b
Community Expert
January 23, 2021

@femkeblanco the .exec method of RegExp is better when you're in a loop. The .match method of String is perfect I think in this case, as @CarlosCanto  shows. I'm only a beginner, too, but I'll add a couple of small details that may be relevent.

var regexp = /(\d+)\s?\//m;

@Marnida I've added a + after the \d which means it will match multi-digits (ie. 'a number' vs. a 'numeral', but only integers—no decimal points matched!). I've also added \s? to replace the space. \s means match any space character and the ? means it might be there or it might not. So it'll match 12 / or 12/. I've also added m directly after the closing slash of the regex. It means 'multiline' and may help, depending on how your strings are formatted.

- Mark

femkeblanco
Brainiac
January 23, 2021

I don't know Regex either, so here's my amateur attempt. Match the first digit-space-slash and convert the object to a new string.  The first character of the new string is your digit.

 

var yourString = "... 1 / ... / ...";
var a = (/\d \//.exec(yourString)).toString();
alert( a[0] );  // 1