简体   繁体   中英

Regex to match @ followed by square brackets containing a number

I want to parse a pattern similar to this using javascript:

@[10] or @[15]

With all my efforts, I came up with this:

@\\[(.*?)\\]

This pattern works fine but the problem is it matches anything b/w those square brackets. I want it to match only numbers. I tried these too:

@\\[(0-9)+\\]

and

@\\[([(0-9)+])\\]

But these match nothing.

Also, I want to match only pattern which are complete words and not part of a word in the string. ie should contain spaces both side if its not starting or ending the script. That means it should not match phrase like this:

abxdcs@[13]fsfs

Thanks in advance.

Use the regex:

/(?:^|\s)@\[([0-9]+)\](?=$|\s)/g

It will match if the pattern ( @[number] ) is not a part of a word. Should contain spaces both sides if its not starting or ending the string.

It uses groups, so if need the digits, use the group 1.

Testing code (click here for demo):

console.log(/(?:^|\s)@\[([0-9]+)\](?=$|\s)/g.test("@[10]")); // true
console.log(/(?:^|\s)@\[([0-9]+)\](?=$|\s)/g.test("@[15]")); // true
console.log(/(?:^|\s)@\[([0-9]+)\](?=$|\s)/g.test("abxdcs@[13]fsfs")); // false
console.log(/(?:^|\s)@\[([0-9]+)\](?=$|\s)/g.test("abxdcs @[13] fsfs")); // true

var r1 = /(?:^|\s)@\[([0-9]+)\](?=$|\s)/g
var match = r1.exec("@[10]");
console.log(match[1]); // 10

var r2 = /(?:^|\s)@\[([0-9]+)\](?=$|\s)/g
var match2 = r2.exec("abxdcs @[13] fsfs");
console.log(match2[1]); // 13

var r3 = /(?:^|\s)@\[([0-9]+)\](?=$|\s)/g
var match3;
while (match3 = r3.exec("@[111] @[222]")) {
    console.log(match3[1]);
}
// while's output: 
// 111
// 222

You don't need so many characters inside the character class. More importantly, you put the + in the wrong place. Try this: @\\\\[([0-9]+)\\\\] .

You were close, but you need to use square brackets:

@\[[0-9]+\]

Or, a shorter version:

@\[\d+\]

The reason you need those slashes is to "escape" the square bracket. Usually they are used for denoting a " character class ".

[0-9] creates a character class which matches exactly one digit in the range of 0 to 9. Adding the + changes the meaning to "one or more". \\d is just shorthand for [0-9] .

Of course, the backslash character is also used to escape characters inside of a javascript string, which is why you must escape them. So:

javascript

"@\\[\\d+\\]"

turns into:

regex

@\[\d+\]

which is used to match:

@ a literal "@" symbol
\\[ a literal "[" symbol
\\d+ one or more digits (nearly identical to [0-9]+ )
\\] a literal "]" symbol

I say that \\d is nearly identical to [0-9] because, in some regex flavors ( including .NET ), \\d will actually match numeric digits from other cultures in addition to 0-9.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM