多行 gnu 正则表达式
我想在新行之后匹配一个表达式。我正在使用 gnu.regexp 和标志 REG_MULTILINE。 这是我想检查的字符串
Hello
Dude
我的方法是使用这个正则表达式来匹配。
String strRegExp = "^[Dd][Uu][Dd]";
但这不起作用。看不出问题出在哪里。 我正在一个简单的单元测试中运行所有这些:
@Test
public void testREMatchAtStartOfNewLine()
throws Exception {
String strRegExp = "^[Dd][Uu][Dd]";
int flags = RE.REG_MULTILINE;
String strText ="Hello\nDude";
RE re = new RE(strRegExp, flags, RESyntax.RE_SYNTAX_PERL5);
REMatch match = re.getMatch (strText);
String strResult = "";
if (match != null) {
strResult = match.substituteInto ("$0");
}
assertEquals("Match at start of new line ", "Dud", strResult); // FAILS
}
提前致谢。 编辑: 为了澄清一下,我正在使用以下导入:
import gnu.regexp.RE;
import gnu.regexp.REMatch;
import gnu.regexp.RESyntax;
I want to match an expression right after a new line. I´m using gnu.regexp and with flag REG_MULTILINE.
Here´s the String I want to check
Hello
Dude
My approach is using this regex to match.
String strRegExp = "^[Dd][Uu][Dd]";
But it does not work. Can´t see where the problem is.
I´m running all this in a simple unit test:
@Test
public void testREMatchAtStartOfNewLine()
throws Exception {
String strRegExp = "^[Dd][Uu][Dd]";
int flags = RE.REG_MULTILINE;
String strText ="Hello\nDude";
RE re = new RE(strRegExp, flags, RESyntax.RE_SYNTAX_PERL5);
REMatch match = re.getMatch (strText);
String strResult = "";
if (match != null) {
strResult = match.substituteInto ("$0");
}
assertEquals("Match at start of new line ", "Dud", strResult); // FAILS
}
Thanks in advance.
edit:
To clarify, I am using following imports:
import gnu.regexp.RE;
import gnu.regexp.REMatch;
import gnu.regexp.RESyntax;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
鉴于主页的下载链接已损坏,您使用 GNU Regex 库的原因是什么? :)
无论如何,当使用
RESyntax.RE_SYNTAX_PERL5
时,似乎需要\r\n
作为行分隔符。将\n
替换为\r\n
似乎可行。Any reason you are using GNU Regex library given that the home page has a broken download link? :)
Anyways, it seems that when using
RESyntax.RE_SYNTAX_PERL5
expects\r\n
as line separator. Replacing\n
with\r\n
seems to work.我不确定您使用的是什么正则表达式,但以下内容对我有用:
请注意模式前面和末尾的
".*"
。默认情况下,Java 正则表达式需要匹配整个字符串,因此这些是必要的。I'm not sure what regex you are using but the following works for me:
Notice the
".*"
at the front and end of the pattern. By default Java regex need to match the entire string so those are necessary.