[英]Need help using regex function/trimming my string
I have been stuck on this for a bit now, my output looks as follows: the first 2 letters represents the hallway number, so 17 for the first one, and the following number represents the shelf number, (location in hallway).我已经卡了一段时间了,我的 output 看起来如下:前两个字母代表走廊编号,所以第一个是 17,后面的数字代表货架编号,(在走廊的位置)。 As you can see in hallway 17 shelf 1 we have either A1 or A, but that doesn't matter.
正如您在走廊 17 架子 1 中看到的那样,我们有 A1 或 A,但这并不重要。 I want the output for 171A1 to be 171, and for 15211 to be 1521, so I want to remove the alphabetic letters at the end combined with the numbers which may follow after.
我希望 171A1 的 output 为 171,而 15211 为 1521,所以我想删除末尾的字母以及后面可能出现的数字。
171A1
171A1
171A
171A0
15211
15211
15211
15210
15190
I tried using string.Remove(string.Length-2) but this doesn't work as we have 171A for example, which should become 171. Any help would be appreciated.我尝试使用 string.Remove(string.Length-2) 但这不起作用,例如我们有 171A,它应该变成 171。任何帮助将不胜感激。
In case you don't need it to be REGEX, this should work如果您不需要它是正则表达式,这应该可以
var rawString = "15211";
var maxLength = 4;
var trimmedResult = new string(
rawString.TakeWhile(char.IsNumber) // loop through characters using LINQ. since your string starts with numbers, you can just keep taking until you bump into a character
.Take(maxLength) // limit the length for cases like "15211" where you don't need the extra numbers in the end
.ToArray() // so we can use the new string() constructor
);
For the part in the question, you can use a pattern with a capture group, and use the group in the replacement:对于问题中的部分,您可以使用带有捕获组的模式,并在替换中使用该组:
^([0-9]{2,}?)[A-Z]?[0-9]?$
^
Start of string ^
字符串开头([0-9]{2,}?)
Capture group 1, match 2 digits 0-9 non greedy ([0-9]{2,}?)
捕获组 1,匹配 2 位 0-9 非贪心[AZ]?[0-9]?
Match an optional char AZ and optional digit 0-9$
End of string $
字符串结尾See a regex demo .查看正则表达式演示。
string pattern = @"^([0-9]{2,}?)[A-Z]?[0-9]?$";
string[] strings = { "171A1", "171A1", "171A", "171A0", "15211", "15211", "15211", "15210", "15190" };
foreach (String s in strings)
{
Console.WriteLine(Regex.Replace(s, pattern, "$1"));
}
Output Output
171
171
171
171
1521
1521
1521
1521
1519
If you want to separate the output by a dot after the 2 digits, you can use 2 capture groups and match at least 1 or more digits in the second group:如果要在 2 位数字后用点分隔 output,可以使用 2 个捕获组并匹配第二组中的至少 1 个或多个数字:
string pattern = @"^([0-9]{2})([0-9]+?)[A-Z]?[0-9]?$";
string[] strings = { "171A1", "171A1", "171A", "171A0", "15211", "15211", "15211", "15210", "15190" };
foreach (String s in strings)
{
Console.WriteLine(Regex.Replace(s, pattern, "$1.$2"));
}
Output Output
17.1
17.1
17.1
17.1
15.21
15.21
15.21
15.21
15.19
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.