简体   繁体   English

正则表达式可将字符串最多匹配两个连续的空格

[英]Regex to match string up to two consecutive spaces

I'm using .NET to experiment with regex's. 我正在使用.NET来测试正则表达式。

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)? 我如何捕获上述字符串的第一部分? This is a test ,知道两个段被两个空格(在regex世界中为\\s )分开了吗?

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). 直到遇到第一个双精度\\s (顺便说一句, \\s并不完全表示“空格”,它表示任何空格,包括换行符,回车符,换页符,制表符)。

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: 我通过这个SO问题找到了解决方案:

Regex to Exclude Double spaces 正则表达式排除双精度空格

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

Will match what I need. 会符合我的需求。

Crazy stuff this regex malarky. 这个正则表达式疯狂的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM