简体   繁体   English

查找两个字符串之间的子字符串

[英]Find substring between two strings

I have a string such as: 我有一个字符串,例如:
file = "UserTemplate324.txt"

I'd like to extract "324". 我想提取“ 324”。 How can I do this without any external libraries like Apache StringUtils? 没有Apache StringUtils之类的任何外部库,我该怎么办?

Assuming you want "the digits just before the dot": 假设您要使用“点之前的数字”:

String number = str.replaceAll(".*?(\\d+)\\..*", "$1");

This uses regex to find and capture the digits and replace the entire input with them. 这使用正则表达式查找和捕获数字,并用数字替换整个输入。

Of minor note is the use of a non-greedy quantifier to consume the minimum leading input (so as not to consume the leading part of the numbers too). 值得注意的是,使用了一个非贪婪量词来消耗最小的前导输入(以免也消耗数字的前导部分)。

If you want to exclude the non-digit characters: 如果要排除非数字字符:

String number = file.replaceAll("\\D+", "");

\\\\D+ means a series of one or more non digit (0-9) characters and you replace any such series by "" ie nothing, which leaves the digits only. \\\\D+表示一个或多个非数字(0-9)字符的序列,您可以用""替换任何这样的序列,即什么也没有,仅保留数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM