[英]java regex match a string
这是一个字符串
* '''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
是没用的,因为点不能与换行符匹配。 (这就是为什么惰性量词也没用的原因)
这会让我觉得有些意义,
Pattern pattern = Pattern.compile("^(\\*[^*].+)");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.