Regular expression to find number in parentheses, but only at beginning of string

拜拜、爱过 提交于 2021-02-04 20:37:54

问题


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.


回答1:


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)

Regex Demo




回答2:


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

Demo



来源:https://stackoverflow.com/questions/30405739/regular-expression-to-find-number-in-parentheses-but-only-at-beginning-of-strin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!