Java 如何从多个带下划线的可变大小字符串中获取所需的字符?
这是我的继续 但包括从中提取人名的其他场景Java 如何从多个带下划线的可变大小字符串中获取所需的字符?,java,string,Java,String,这是我的继续 但包括从中提取人名的其他场景 pot-1_Sam [Sam is the word to be extracted] pot_444_Jack [Jack is the word to be extracted] pot_US-1_Sam [Sam is the word to be extracted] pot_RUS_444_Jack[Jack is the word to be extracted] pot_UK_3_Nick_Samuel[Nick_Samue
pot-1_Sam [Sam is the word to be extracted]
pot_444_Jack [Jack is the word to be extracted]
pot_US-1_Sam [Sam is the word to be extracted]
pot_RUS_444_Jack[Jack is the word to be extracted]
pot_UK_3_Nick_Samuel[Nick_Samuel is the word to be extracted]
pot_8_James_Baldwin[James_Baldwin is the word to be extracted]
pot_8_Jack_Furleng_Derik[Jack_Furleng_Derik is the word to be extracted]
上面是要从中提取人名的示例单词。需要注意的是,人名总是以“数字”和“下划线”开头。如何使用Java实现上述功能 这里是正则表达式:
\d.(.*$)
\d代表一位数字
_代表下划线
()代表团体
.*$表示“行结束前的所有”使用以下正则表达式:
^.*\d+_(.*)$
。。。并提取第一组的值。您可以尝试使用反射来获取变量的实际名称,如图所示
String str= "pot_8_Jack_Furleng_Derik";
// name starts after number and _
Pattern p = Pattern.compile("\\d+_");
Matcher m = p.matcher(str);
int index = -1;
// find the index of name
if(m.find())
index = m.start()+2;
str= str.substring(index);
System.out.print(str);
您可以使用Regex进一步分解它,正如前面提到的那样也许您可以使用Regex?
String[] strings = {
"pot-1_Sam",
"pot_444_Jack",
"pot_US-1_Sam",
"pot_RUS_444_Jack",
"pot_UK_3_Nick_Samuel",
"pot_8_James_Baldwin",
"pot_8_Jack_Furleng_Derik"
};
Pattern pattern = Pattern.compile("\\d_(\\w+)$");
for (String s : strings ){
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
}