0

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. 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. 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.

4

3 回答 3

3

这里你有一个无效的转义序列:

"...(?<=String1\sString..."
               ^^

您必须转义 java String 中的反斜杠文字才能将其传递到正则表达式模式:

"...(?<=String1\\sString..."
               ^^^

您已经正确使用\\dfor 数字,但不适\\s用于 for 空格。

于 2013-08-05T14:24:08.030 回答
2

您的正则表达式以:

\\d?=\sString3\sString4)

在那里,您似乎错过了一个左方括号以使其成为正向前瞻,当然\s应该是\\s. 将该部分更改为:

\\d(?=\\sString3\\sString4)
于 2013-08-05T14:30:09.983 回答
1

我知道很多人不知道精彩课的特点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();
}
于 2013-08-05T15:39:23.190 回答