这是一个字符串
* '''A happy man is too satisfied with the present to dwell too much on the future.'''
** "My Future Plans" an essay written at age 17 for school exam (18 September 1896) ''The Collected Papers of Albert Einstein'' Vol. 1 (1987) Doc.22
我需要获取仅以一个 * 开头直到该行结尾的文本
Pattern pattern = Pattern.compile("\\*(.+?)\\n");
Matcher matcher = pattern.matcher(text);
List<String> s = new ArrayList<String>();
while (matcher.find()) {
s.add(matcher.group(1));
}
我试过上面的代码,但它甚至匹配 2 * 而且从 * 到新行的文本也没有正确出现,我在这里错过了什么?
最佳答案
你可以试试这个:
Pattern pattern = Pattern.compile("(?m)^\\*([^*].*)");
(?m)
在多行模式下设置模式,其中 ^
表示“行的开头”
在末尾添加 \\n
是没有用的,因为点不能匹配换行符。 (这也是惰性量词无用的原因)
关于java正则表达式匹配一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20012851/