如何从字符串中提取子字符串
我有一个字符串,它看起来并不总是相同,并且我想从这个字符串中提取一些信息(如果存在)。该字符串可能类似于以下内容之一:
myCommand -s 12 moreParameters
myCommand -s12 moreParamaters
myCommand -s moreParameters
我想获取数字,即本例中的 12(如果存在)。我怎样才能做到这一点?
非常感谢!
编辑:字符串有第四个可能的值:
myCommand moreParameters
如何修改正则表达式以涵盖这种情况?
I have a string, that does not always look the same, and from this string I want to extract some information if it exists. The string might look like one of the following:
myCommand -s 12 moreParameters
myCommand -s12 moreParamaters
myCommand -s moreParameters
I want to get the number, i.e. 12 in this case, if it exists. How can I accomplish that?
Many thanks!
EDIT: There is a fourth possible value for the string:
myCommand moreParameters
How can I modify the regex to cover this case as well?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
这将匹配
-s
最后跟上空格和数字;并将整个字符串替换为数字。编辑:该字符串还有第四个可能的值:
myCommand moreParameters
如何修改正则表达式以涵盖这种情况?
Try this:
This will match a
-s
eventually followed by spaces and digits; and replace the whole string by the digits.EDIT: There is a fourth possible value for the string:
myCommand moreParameters
How can I modify the regex to cover this case as well?
您无需外部工具即可完成所有这些工作
You can do all these without the need for external tools