[英]Java Regex pattern, surrounded by multiple strings
This is a continuation of a question I asked earlier. 这是我先前提出的问题的延续。 I need to extract a date pattern, which is surrounded by the strings String1, String2, String3 String4.
我需要提取一个日期模式,该模式被字符串String1,String2,String3和String4包围。 What I did was
我所做的是
Pattern pattern = Pattern.compile("(?<=String1\sString2\s(?:0?[1-9]|[12][0-9]|3[01])([- /.])(?:0?[1-9]|1[012])\\1(?:19|20)?\\d\\d?=\sString3\sString4)");
my date pattern is 我的约会方式是
(0?[1-9]|[12][0-9]|3[01])([- /.])(0?[1-9]|1[012])\\2(19|20)\\d\\d
which works fine but when trying to surround it with strings, I am facing trouble. 效果很好,但是当尝试用字符串将其包围时,我面临麻烦。
The date is in between String2 and String3. 日期在String2和String3之间。 I am quite sure there is something wrong, as there is an error on my program saying invalid escape sequence but I can't figure it out.
我很确定有什么问题,因为我的程序出现错误,指出无效的转义序列,但我无法弄清楚。 Any help is appreciated.
任何帮助表示赞赏。 Thanks in advance.
提前致谢。
Here you have an invalid escape sequence: 这是无效的转义序列:
"...(?<=String1\sString..."
^^
You have to escape the backslash literal in a java String to pass it into a regular expression pattern: 您必须在Java字符串中转义反斜杠文字才能将其传递给正则表达式模式:
"...(?<=String1\\sString..."
^^^
You already had it right with the \\\\d
for digits, but not with the \\\\s
for whitespace. 您已经正确使用
\\\\d
作为数字,但没有使用\\\\s
作为空格。
Your regex is ending with: 您的正则表达式以:
\\d?=\sString3\sString4)
There it looks like you missed an opening square bracket to make it positive lookahead and of course \\s
should be \\\\s
. 那里好像您错过了方括号使它成为正面的前瞻 ,当然
\\s
应该是\\\\s
。 Change that part to: 将该部分更改为:
\\d(?=\\sString3\\sString4)
I know that many people are not aware of the features of the wonderful class MessageFormat
, so here a quick reminder: 我知道很多人都不知道出色的
MessageFormat
类的功能,因此在此提醒一下:
MessageFormat format = new MessageFormat("String1 String2 {0,date} String3 String4");
try {
Object[] parse = format.parse("String1 String2 31.8.2000 String3 String4");
Date date = (Date) parse[0];
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.