Java,在$符号之间提取单词 [英] Java, extracting words between $ symbol
本文介绍了Java,在$符号之间提取单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用Java提取美元符号$
之间的单词.
Using Java, I want to extract the words between the dollarsign symbol $
.
例如:
String = " this is first attribute $color$. this is the second attribute $size$"
我想拉出字符串:color
和size
并将它们放入列表中.
I want to pull out the strings: color
and size
and put them into a List.
我尝试过:
Pattern pattern = Pattern.compile("(\\$) .* (\\$)");
Matcher matcher = pattern.matcher(sentence);
但是我得到了输出:
"$color$.this is the second attribute $size$"
做到这一点的最佳方法是什么?
What is the best way to do this?
推荐答案
问题是您使用的正则表达式贪婪,并且消耗了字符串中从第一个$
到最后一个$
的所有内容.您必须在*
之后添加一个?
,以使正则表达式变得非贪婪:
The problem is that the regex you are using is greedy and consumes everything beginning at the first $
until the last $
in your string. You have to add a ?
after the *
to make the regex nongreedy:
Pattern pattern = Pattern.compile("\\$(.*?)\\$");
Matcher matcher = pattern.matcher(sentence);
List<String> result = new ArrayList<String>();
for(int i=1; i <= matcher.groupCount(); i++)
result.add(matcher.group(i);
这篇关于Java,在$符号之间提取单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文