Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match certain characters anywhere between two characters

Tags:

regex

I want to detect (and return) any punctuation within brackets. The line of text I'm looking at will have multiple sets of brackets (which I can assume are properly formatted). So given something like this:

[abc.] [!bc]. [.e.g] [hi]

I'd want to detect all those cases and return something like [[.], [!], [..]].

I tried to do /{.*?([.,!?]+).*?}/g but then it returns true for [hello], [hi] which I don't want to match!

I'm using JS!

like image 358
www Avatar asked Oct 18 '25 02:10

www


1 Answers

You can match substrings between square brackets and then remove all chars that are not punctuation:

const text = '[abc.] [!bc]. [.e.g]';
const matches = text.match(/\[([^\][]*)]/g).map(x => `[${x.replace(/[^.,?!]/g, '')}]`)
console.log(matches);

If you need to make your regex fully Unicode aware you can leverage ECMAScript 2018+ compliant solution like

const text = '[abc.] [!bc、]. [.e.g]';
const matches = text.match(/\[([^\][]*)]/g).map(x => `[${x.replace(/[^\p{P}\p{S}]/gu, '')}]`)
console.log(matches);

So,

  • \[([^\][]*)] matches a string between [ and ] with no other [ and ] inside
  • .replace(/[^.,?!]/g, '') removes all chars other than ., ,, ? and !
  • .replace(/[^\p{P}\p{S}]/gu, '') removes all chars other than Unicode punctuation proper and symbols.
like image 62
Wiktor Stribiżew Avatar answered Oct 20 '25 06:10

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!