简体   繁体   中英

Regex Select [A-Z ] except two consecutive spaces

I've been trying to create a regex to match all letters from AZ and a single space. I want it to stop when it becomes more than 1 consecutive space. I also do not want the dash included. This is being called and returned as a string in a C# based program. I plan to just crop the string at the end by 1 after I have imported it to remove the space at the end (if it ends up being returned by regex).

TERRA MARVELLOUS LUX      -

So far I've tried a multitude of expressions the best I can come up with so far is

^[A-Z (?!\s{2,})]*

as well as

^[A-Z ]*(?:\s{2})

and so on I could list more I've been trying. I'm quite stuck.

^[A-Z ]+\b

You can try this.See demo.

https://regex101.com/r/tJ2mW5/20

This should solve your issue:

([A-Z]+[ ]{1})+

The main idea is to match all the groups of at least one character of AZ, then have one space and match the pattern at least one time.

And the example: https://regex101.com/r/tJ2mW5/21

If you want to just strip final spaces with hyphen, you can use

 var t1 = "TERRA MARVELLOUS  LUX      -";
 var rx2 = new Regex(@"\s+\-?$");
 var res = rx2.Replace(t1, string.Empty);

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