Home > database >  Write a regular expression that finds strings of the following kind
Write a regular expression that finds strings of the following kind

Time:11-02

The task itself looks like this: Given string 'ave a#b a2b a$b a4b a5b a-b acb'. Write a regular expression that finds strings of the following kind: the letters 'a' and 'b' are at the edges, and there is neither a letter nor a number between them.

It's just really hard for me to make sense of it. But I was able to write something like:

'ave a#b a2b a$b a4b a5b a-b acb'.replace(/a\Wb/g, ""),

but it works by replacing only the values I need to output and leaving 'ave a2b a4b a5b acb', but I just need to remove everything except 'a#b a$b a-b'. Can you help me with that?

CodePudding user response:

You can match all occurrences of the \ba[^\sa-zA-Z0-9]b\b pattern that matches a not preceded with any word char, then any char other than whitespace, letters and digits, and then a b not followed by a word char, and then join the output with a space:

console.log(
  'ave a#b a2b a$b a4b a5b a-b acb'.match(/\ba[^\sa-zA-Z0-9]b\b/g).join(" ")
)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

See the regex demo.

Note: if the expected matches occur in between whitespaces or start/end of string, you might need to replace word boundaries with whitespace boundaries, /(?<!\S)a[^\sa-zA-Z0-9]b(?!\S)/g.

  • Related