1

Hi i am new to programming and i would like to find if a particular pattern exists in a string.

I have a string "i am [1234@some data] some data given to [223@123some data]"

I want to check if the string contains pattern like [1234@some data] or [223@123some data] is present. So it includes square-bracket followed by one or more digits followed by one @ character followed by zero or more digits followed by one or more alphabets followed by space and one or more alphabets.

What i have tried?

const string = "i am [1234@some data] some data given to [223@123some data]"
const pattern_present = string.match((/^\d+\@+\w+$/)

This doesnt seem to work. Could someone help me with this

1
  • 3
    Why ^ and $? Use \[ and ] instead. Use /\[(\d+@[\w\s]+)]/g. You may as well use /\[([^\][]*)]/g to get all strings inside square brackets. Commented Aug 28, 2019 at 11:11

4 Answers 4

1

You may use

/\[(\d+@[\w\s]+)]/g

See the regex demo and the regex graph:

enter image description here

Note you may match any chars but [ and ] after @:

/\[(\d+@[^\][]+)]/g
        ^^^^^^ 

JS demo:

const string = "i am [1234@some data] some data given to [223@123some data]"
let matches = [...string.matchAll(/\[(\d+@[\w\s]+)]/g)];
console.log(Array.from(matches, m => m[0])); // Full matches with square brackets
console.log(Array.from(matches, m => m[1])); // Captures only without square brackets

Sign up to request clarification or add additional context in comments.

Comments

0
(\[[0-9]{1,}@[0-9a-zA-Z]{1,}\s[a-zA-Z]{1,})

so:

  • square-bracket is a reserved character so we use escape char \ to refer to it like a simple cahr
  • [0-9] it's a pattern of a digit from 0 to 9.
  • {1,} this is the number of appearance of what you are searching so: [0-9]{1,} means 1 digit or more.

  • @ is the character that you are looking

  • [0-9a-zA-Z]{1,} : any appearance of digits or characters
  • \s : that is for space
  • [a-zA-Z]{1,} : any appearance of characters

Comments

0

For example - /[\d+@.+?]/mg For matching a few substrings you should add flag "g" and for multiline search "m"

Comments

0

You can use the following regex:

/\[\d+@\d*[a-zA-Z]+\s[a-zA-Z]+\]/g

1 Comment

Why use mi? They are not useful with your pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.