admin管理员组

文章数量:1401184

My title can look like

(10) - lorem ipsum
(101) - lorem ipsum
(1) - lorem ipsum
lorem ipsum

I want to check if my title contains (number) at the start

string.match(/^(+[0-9]+)+$/);

I'm not good on regex, can someone help and say what is wrong ?

My title can look like

(10) - lorem ipsum
(101) - lorem ipsum
(1) - lorem ipsum
lorem ipsum

I want to check if my title contains (number) at the start

string.match(/^(+[0-9]+)+$/);

I'm not good on regex, can someone help and say what is wrong ?

Share Improve this question edited Feb 29, 2016 at 9:44 Dave R. 7,3033 gold badges32 silver badges53 bronze badges asked Feb 29, 2016 at 9:40 WizardWizard 11.3k38 gold badges99 silver badges167 bronze badges 2
  • 1 If you want to just check, use RegExp.test() rather than String.match() unless you need the value itself. – Wiktor Stribiżew Commented Feb 29, 2016 at 9:44
  • Adam's answer should be correct, will require ( to be first character on the string, followed by 1 or more numbers and then ). @WiktorStribiżew I usually use this idiom; if( /^\[0-9]+\)/.test(string) ) – mschr Commented Feb 29, 2016 at 9:51
Add a ment  | 

2 Answers 2

Reset to default 8

Just remove the $ from your regex, and escape the parentheses.

string.match(/^\([0-9]+\)/);

$ means end of string.

( and ) are special character and should be escaped. Pharenthesis are used for grouping. You can find a list of special characters here.

Use test method to return whether condition is true or false, Whether it starting with number or not.

/^\([0-9]+\)/.test(string);

OR

var patt = new RegExp(/^\([0-9]+\)/);
patt.test(string);

本文标签: javascriptCheck if a string starts with a number in parenthesesStack Overflow