1

I'm using .NET to experiment with regex's.

I'm struggling to compose a regex to capture a segment in a string that ends with two spaces. For example

This is a test  Start of next bit

How can I capture the first portion of the above string This is a test, knowing that the two segments are split by two spaces (\s in the regex world)?

I've tried stuff like:

This is a test[^\s{2}]

but that's getting me nowhere.

2 Answers 2

1

A more standard regex than the one that you have would be:

This.*?(?=\s{2})

It matches any character .*? until it encounters the first double \s (by the way, \s doesn't exactly mean 'space', it means any whitespace, including newlines, carriage returns, formfeeds, tabs).

Or you could try something a little different; match everything as long as they are single 'spaces':

This(?:\s\S+)*

Then again, it's simpler to split on the double space.

Sign up to request clarification or add additional context in comments.

Comments

0

I found a solution via this SO question:

Regex to Exclude Double spaces

This((?!\s{2}).)*

Will match what I need.

Crazy stuff this regex malarky.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.