Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - matching all between second set of brackets ([])

Tags:

regex

php

I have the following string that I need to match only the last seven digets between [] brackets. The string looks like this

[15211Z: 2012-09-12] ([5202900])

I only need to match 5202900 in the string contained between ([]), a similar number could appear anywhere in the string so something like this won't work (\d{7})

I also tried the following regex

([[0-9]{1,7}])

but this includes the [] in the string?

like image 327
Elitmiar Avatar asked May 20 '13 08:05

Elitmiar


People also ask

Can a regex identify correct bracketing?

Regular expressions can't count brackets.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

How do you match curly brackets in regex?

To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.

How do you escape braces in regular expression?

Find that brace and escape it with a backslash in front on it: \{ . You can also put it in a character class: [{] . You might have to do this in code for tools that you didn't write (I did it for my local autotools, for instance).


2 Answers

If you just want the 7 digits, not the brackets, but want to make sure that the digits are surrounded with brackets:

(?<=\[)\d{7}(?=\])

FYI: This is called a positive lookahead and positive lookbehind.

Good source on the topic: http://www.regular-expressions.info/lookaround.html

like image 99
ATN Avatar answered Oct 13 '22 19:10

ATN


Try matching \(\[(\d{7})\]\), so you match this whole regular expression, then you take group 1, the one between unescaped parentheses. You can replace {7} with a '*' for zero or more, + for 1 or more or a precise range like you already showed in your question.

like image 36
Maarten Bodewes Avatar answered Oct 13 '22 20:10

Maarten Bodewes