Herbert Feichtinger
Herbert Feichtinger

Reputation: 165

How to split string into words including delimiters

How can I split a text into words in .NET, returning both the words and their separators and punctuation marks.

Input:

"Hello world! What's up?"

Output: 'Hello', ' ', 'world', '!', ' ','What's',' ','up','?'

Upvotes: 0

Views: 113

Answers (3)

A pant
A pant

Reputation: 11

Use this regular expression:

'(?=[^\w'])|(?<=[^\w'])`

Upvotes: -2

Jens Meinecke
Jens Meinecke

Reputation: 2940

var output = Regex.Split(input, "([^A-Z0-9])", RegexOptions.IgnoreSpace);

Upvotes: 0

vks
vks

Reputation: 67968

(?=[^\w'])|(?<=[^\w'])

You can split by this.See demo.

https://regex101.com/r/iJ7bT6/15

Upvotes: 4

Related Questions