我想从用户提供的搜索字符串中分割出澳大利亚邮政编码.
澳大利亚邮政编码是格式的4位数字'0000' - '9999'.
用户应该能够键入"Searchterm 2000 3000"和字符串,2000并且3000应该分成单独的变量,以便在后端我可以根据搜索词过滤邮政编码.
我可以在正则表达式匹配上做一个foreach:
foreach (var match in Regex.Matches(str, @"<not sure what the regex entry is>"))
Run Code Online (Sandbox Code Playgroud)
但是,如何从字符串中删除那些匹配,以便我留下搜索词?(可以是多个单词)
我建议使用正则表达式(提取4位数字)和Linq(组织它们):
string source = "Searchterm 2000 3000";
// "2000 - 3000"
string result = string.Join(" - ", Regex
.Matches(source, "[0-9]{4}")
.OfType<Match>()
.Select(match => match.Value)
.Take(2));
Run Code Online (Sandbox Code Playgroud)
如果您想要将邮政编码的部分分开,只需删除string.Join:
// parts[0] == 2000; parts[1] == 3000
string[] parts = Regex
.Matches(source, "[0-9]{4}")
.OfType<Match>()
.Select(match => match.Value)
.Take(2)
.ToArray();
Run Code Online (Sandbox Code Playgroud)