我有一个字符串:
嘿,我的名字是$name$; 我$years$岁了,我喜欢打$sport$并且我住在$country$!
现在我想要得到每个$符号中间单词的长度,并将其存储在一个Map中,例如我的例子中Map应该是:
- name -> 4
- years -> 5
- sport -> 5
- country -> 7
一开始我考虑在我的函数中进行递归调用,但是我找不到方法?
我有一个字符串:
嘿,我的名字是$name$; 我$years$岁了,我喜欢打$sport$并且我住在$country$!
现在我想要得到每个$符号中间单词的长度,并将其存储在一个Map中,例如我的例子中Map应该是:
一开始我考虑在我的函数中进行递归调用,但是我找不到方法?
String x = "Hey my name is $name$; I have $years$ years old," +
"and I love play $sport$ and I live in $country$ !";
Pattern p = Pattern.compile("\\$\\w+\\$");
Matcher m = p.matcher(x);
Map<String, Integer> map = new LinkedHashMap<>();
while(m.find()) {
String in = m.group().substring(1,m.group().length()-1);
map.put(in, in.length());
}
$a$
中的单个字符,而且该映射将会忽略可能不希望出现的重复。 - Michael(.).*\1
搜索以相同字符开头和结尾的单词。String x = "Hey my name is $name$; I have $years$ years old, and I love play $sport$ and I live in $country$ !";
//regex to get the words between $
Matcher m = Pattern.compile("\\$(.*?)\\$").matcher(x);
List<String> l = new ArrayList<>();
//place those matchs in a list
while (m.find()) {
l.add(m.group(1));
}
System.out.println(l);
//collect those into a Map
Map<String, Integer> result = l.stream().collect(Collectors.toMap(q -> q, q -> q.length()));
System.out.println(result);
{国家=7,名称=4,运动=5,年份=5}
group(1)
,你可以直接使用 group()
。 - Michael你可以使用流。
public void test() {
String s = "Hey my name is $name$; I have $years$ years old, and I love play $sport$ and I live in $country$ !";
// Helps me maintain state of whether we are in a word or not.
// Use AtomicBoolean as a `final` mutable value.
final AtomicBoolean inWord = new AtomicBoolean(false);
// Split on the `$` character and stream it.
Map<String, Integer> myMap = Arrays.stream(s.split("\\$"))
// Filter out the non-words (i.e. every other one).
.filter(w -> inWord.getAndSet(!inWord.get()))
// Generate the map.
.collect(Collectors.toMap(w -> w, w -> String::length));
System.out.println(myMap);
}
输出:
{国家=7,名称=4,运动=5,年份=5}