Regex to pick numbers between the second and third "/"

Asked

Viewed 1,632 times

1

Let’s say I have the following string /product/976935/
How would I make a regex to return only the numbers between the second and third bar?
The amount of numbers varies so it’s no use just returning the numbers

2 answers

4


If it’s always product, you can do:

/produto/(\d+)/

(regexplained)

If prefix changes depending on case use:

/(\w+)/(\d+)/

(regexplained)

Note that I also captured the prefix in this case.

Depending on the language it may be necessary to add escapes in the sliders. Swap / for \/.

  • didn’t know this one regexplained

  • I didn’t know him either... very well

  • But what about when the String is /product/976935/xxx5.html ? Would it take the 5 as well? I need all digits between the second and third bar occurrences

  • @Mauro no. would take only what is between the bars, following the pattern described.

1

If you want to remove any text, just use the following expression

"[^0-9]" ou "[^\\d]" 

If it is /product/976935/ he will return 976935, but if it is /product/976935/1 he will return tbm the number 1 and would stay 9769351

In java I think it would look something like this:

 var soNumero = soNumero.replaceAll("[^0-9]",""); 

or

 var soNumero = soNumero.replaceAll("[^\\d]",""); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.