简体   繁体   中英

Regex to match string up to two consecutive spaces

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.

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.

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.

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