leo*_*ora 2 c# regex string parsing
我有以下示例字符串
"CTS3010 - 6ppl"
Run Code Online (Sandbox Code Playgroud)
要么
"CTs3200 - 14ppl"
Run Code Online (Sandbox Code Playgroud)
要么
"CTS-500 2ppl"
Run Code Online (Sandbox Code Playgroud)
我需要解析这些字符串中的数字.在字符串末尾的"ppl"之前解析数字的最佳方法是什么.我需要正则表达式吗?我有向后循环的逻辑,但感觉这里有一个更优雅的解决方案.
这些只是示例,但所有示例似乎都遵循相同的模式
您可以执行此操作以在"ppl"之前获取数字:
using System.Text.RegularExpressions;
...
Regex regex = new Regex("([0-9]+)ppl");
string matchedValue = regex.Match("CTS-500 122ppl").Groups[1].Value;
Run Code Online (Sandbox Code Playgroud)
在这种情况下matchedValue将是122.
如果你想要安全,并且你知道"ppl"将始终位于字符串的末尾,我会将正则表达式更改为:( "([0-9]+)ppl$"唯一的区别是最后的美元符号).