![](/img/trans.png)
[英]How to search a word in the middle of the sentence using regular expression in java
[英]How to match a number in the middle using regular expression in Java?
例如:
start 2 4 9
end 5 8 39
如何使用正则表达式匹配4和8? 谢谢!
我在上面评论了一个非正则表达式解决方案。 这是用伪代码编写的,如果这个想法成立,那么可以很容易地交叉应用到Java。
我的评论:
另外,为什么需要使用正则表达式? 为什么不在每个a-zA-Z处分开...然后在每个空格之间分开? 例如1 2 3 abc 4 5 6 def 7 8 9-> 1 2 3,abc 4 5 6,def 7 89。然后将每个空格分开,第一种情况将是第二个元素,其他情况将中间的数字是第三要素。 如果您想让我详细说明,请在下面进行。 只是问清楚为什么要使用正则表达式?
伪编码示例:
theString = "1 2 3 abc 4 5 6 def 7 8 9"
theString = theString.toLower() //lower case for ease of matching
splitS = theString.split([a-Z])
middleNum=[]
middleNum.add(splitS[0][1]) //the 2nd element of the 1st element in the array.
for int i =1; i<splitS.len; i++){
middleNum.add(splitS[i][2])
}
return middleNum //the middle numbers
// or you can stringily it and return a string vs. array.
//让我知道这是否是您要使用正则表达式的目的。 正则表达式不一定会使这个问题变得更容易。 如果我错了,请更正我,但是与拆分相比效率没有太大提高,因为它是第二个数字并且由非数字字符拆分,因此要进行大量的前进/后退检查。
这也使您可以更轻松地更改所需的输出。 例如,如果您想更改为下一个数字,因为数字字符串现在为4个字符,则很容易理解您在做什么。 我假设如果您正在拆分字符串,那么您对Java还是比较陌生的。
使用正则表达式的解决方案, \\\\d+
匹配数字, \\\\s+
匹配数字之间的空格, (\\\\d+)
括号捕获中间数字。
public static Integer extractMiddleNumber(String source) {
Matcher matcher = Pattern.compile("\\d+\\s+(\\d+)\\s+\\d+").matcher(source);
if (matcher.find()) {
return Integer.parseInt(matcher.group(1));
}
return null; //not found, you can throw exception if you prefer
}
由于每行只有三个数字,因此您可以使用下面的正则表达式来捕获第二个数字并将其存储到组1中。
^\D*\d+\D*(\d+)\D*\d+\D*$
例:
String s = "start 2 4 9";
Pattern regex1 = Pattern.compile("^\\D*\\d+\\D*(\\d+)\\D*\\d+\\D*$");
Matcher regexMatcher = regex1.matcher(s);
if (regexMatcher.find()) {
String ResultString = regexMatcher.group(1);
System.out.println(ResultString);
}
我会这样
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* thanks http://txt2re.com/index-java.php3?s=start%202%204%209&-1&9&3&10&4&11&5
*/
public class Regex {
public static void main(String[] args) {
String[] txt = { "start 2 4 9", "end 5 8 39" };
for (String s : txt) {
match(s);
}
}
private static void match(String txt) {
String re1 = "(start|end)"; // Word 1
String re2 = "(\\s+)"; // White Space 1
String re3 = "(\\d+)"; // Integer Number 1
String re4 = "(\\s+)"; // White Space 2
String re5 = "(\\d+)"; // Integer Number 2 <==========
String re6 = "(\\s+)"; // White Space 3
String re7 = "(\\d+)"; // Integer Number 3
Pattern p = Pattern.compile(re1 + re2 + re3 + re4 + re5 + re6 + re7,
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(txt);
if (m.find()) {
// String word1=m.group(1);
// String ws1=m.group(2);
// String int1=m.group(3);
// String ws2=m.group(4);
String int2 = m.group(5);
// String ws3=m.group(6);
// String int3=m.group(7);
System.out.println(int2);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.