如果我有一个具有以下字符序列的键:_(some number)_1.我如何才能返回(some number).
例如,如果关键是_6654_1我只需要价值6654.让我感到困惑的问题/问题是数字可能是任何长度,就像_9332123425234_1在这种情况下我只需要9332123425234.
这是我到目前为止所尝试的:
Pattern p = Pattern.compile("_[\\d]_1");
Matcher match = p.matcher(request.getParameter("course_id"));
Run Code Online (Sandbox Code Playgroud)
但这不会涵盖中间数字可以是任何数字(不只是四位数)的情况吗?
你可以弄明白indexOf('_')然后再使用substring.不需要正则表达式.
...但是既然你要求正则表达式,那么你去:
import java.util.regex.*;
class Test {
public static void main(String[] args) {
String str = "_6654_1";
Pattern p = Pattern.compile("_(\\d+)_1");
Matcher m = p.matcher(str);
if (m.matches())
System.out.println(m.group(1)); // prints 6654
}
}
Run Code Online (Sandbox Code Playgroud)
(这里是substring比较的方法:)
String str = "_6654_1";
String num = str.substring(1, str.indexOf('_', 1));
System.out.println(num); // prints 6654
Run Code Online (Sandbox Code Playgroud)
最后的解决方案,使用简单的split("_"):
String str = "_6654_1";
System.out.println(str.split("_")[1]); // prints.... you guessed it: 6654
Run Code Online (Sandbox Code Playgroud)