Reputation: 31
Disclaimer: I'm new to writing regular expressions, so the only problem may be my lack of experience.
I'm trying to write a regular expression that will find numbers inside of parentheses, and I want both the numbers and the parentheses to be included in the selection. However, I only want it to match if it's at the beginning of a string. So in the text below, I would want it to get (10), but not (2) or (Figure 50).
(10) Joystick Switch - Contains control switches (Figure 50)
Two (2) heavy lifting straps
So far, I have (\(\d+\))
which gets (10) but also (2). I know ^ is supposed to match the beginning of a string (or line), but I haven't been able to get it to work. I've looked at a lot of similar questions, both here and on other sites, but have only found parts of solutions (finding things inside of parentheses, finding just numbers at the beginning for a string, etc.) and haven't quite been able to put them together to work.
I'm using this to create a filter in a CAT tool (for those of you in translation) which means that there's no other coding languages involved; essentially, I've been using RegExr to test all of the other expressions I've written, and that's worked fine.
Upvotes: 3
Views: 10291
Reputation: 103874
Like so:
^\(\d+\)
^
anchor
Each of (
and )
are regex meta character, so they need to be escaped with \
So \(
and \)
match literal parenthesis.
(
and )
captures.
\d+
match 1 or more digits
Upvotes: 2
Reputation: 26667
The regex should be
^\(\d+\)
^
Anchors the regex at the start of the string.
\(
Matches (
. Should be escaped as it has got special meaning in regex
\d+
Matches one or more digits
\)
Matches the )
Capturing brackets like (\(\d+\))
are not necessary as there are no other characters matched from the pattern. It is required only when you require to extract parts from a matched pattern
For example if you like to match (50)
but to extract digits, 50
from the pattern then you can use
\((\d+)\)
here the \d+
part comes within the captured group 1, That is the captured group 1 will be 50
where as the entire string matched is (50)
Upvotes: 8