简体   繁体   中英

Regex split sentence into multiple groups

Regex Expression for sentence split needed.
I need a Regex approach to split a sentence up.
The following sentence structure needs to be broken into its component parts:

Question, Options, AnswerType divided by the following delimiters...

Question :  OptionA, OptionB, OptionC   ?   AnswerType

EXAMPLES:
Color: Yellow, Green, Red ? ListBox
Color ? ListBox

As you can see, the second example has no options and this needs to be accounted for. The output would ideally look like the following groups

I am working in VB.NET if that makes any difference.

I don't know how regex works in vb.net but here's a general patter and well explained in the DEMO

Regex:

(?P<question>\\w+)\\s*(?::\\s*(?P<options>\\w+(?:,\\s*\\w+)*))?\\s*\\?\\s*(?P<type>\\w+)

The ?P< name> determines a name for backreferencing that group, you would just loop and you will have everything grouped.

Try out the new regex with the (suffix): DEMO I just added the possibility of having (sufix) after the question.

The Updated regex:

(?P<question>\\w+)\\s*(?P<suffix>\\(\\w+\\))?\\s*(?::\\s*(?P<options>\\w+(?:,\\s*\\w+)*))?\\s*\\?\\s*(?P<type>\\w+)

UPDATE 2: Working with spaces and ' -> (?P<question>[\\w '-]+)\\s*(?P<suffix>\\([\\w '-]+\\))?\\s*(?::\\s*(?P<options>[\\w '-]+(?:,\\s*[\\w '-]+)*))?\\s*\\?\\s*(?P<type>[\\w '-]+)

DEMO

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