Home > Net >  Regular Expression matching Sentence that MAY contain Parantheses
Regular Expression matching Sentence that MAY contain Parantheses

Time:06-22

Am using this expression in REGEX to capture words being sent to our data quality systems. This should be a FULL match - ie all the words in a sentence: (^$|^\w (\s\w )*$)

This works for all scenarios like this:

A sheep jumped over a fence

But not for this

A sheep jumped over a fence (And Tripped)

I understand that \w takes care of only alphanumeric and underscore. But I would also want this to match sentences with the Brackets ( ) like in the example above. Is there a way to achieve this to ADDITIONALLY add the ( ) checks so both scenarios can be satisfied?

CodePudding user response:

I might be misunderstanding this (always take whatever Wiktor says over anybody else) but maybe you are looking for something simple to match each word like this?

^$|([\w] )

or a full match like this

^$|([ \w()] )

Good luck! A good place to try this stuff out is at https://regex101.com/ :) What is neat with regexes is you can make them really clever and small, but I lean towards the side of being able to read easily later. Use whichever one gets it done and is easy to understand.

  • Related