Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

RegEx for getting the first number before the first slash

Explorer ,
Jan 23, 2021 Jan 23, 2021

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!

 

TOPICS
Scripting
5.7K
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 5 Correct answers

Guide , Jan 23, 2021 Jan 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

 

Translate
Community Expert , Jan 23, 2021 Jan 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

...
Translate
Community Expert , Jan 23, 2021 Jan 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 charac

...
Translate
Community Expert , Jan 25, 2021 Jan 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("^[
...
Translate
Enthusiast , Jan 29, 2021 Jan 29, 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 /
...
Translate
Adobe
Guide ,
Jan 23, 2021 Jan 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

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 23, 2021 Jan 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

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 23, 2021 Jan 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

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 25, 2021 Jan 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

😉

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 28, 2021 Jan 28, 2021

@Marnida 

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

 

Or why don't you give any feedback?

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Jan 29, 2021 Jan 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.

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Enthusiast ,
Jan 29, 2021 Jan 29, 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.

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Feb 01, 2021 Feb 01, 2021

Thanks @Inventsablethat looks great! In my head I was looking for a pure RegExp solution in an attempt to better understand how it works.When I get a chance this week, I'll spend some time playing with it, get my head round what's going on, and come back.

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Feb 05, 2021 Feb 05, 2021
LATEST

Please, do not forget:

3. 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 …

 


By @Marnida

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines