Java 由于换行符(\n)导致正则表达式中断
我有一个正则表达式,它使用Java 由于换行符(\n)导致正则表达式中断,java,regex,Java,Regex,我有一个正则表达式,它使用“'.*?'|'.*?”模式查找三重引号(''')和单引号(')之间的文本。当回车被添加到输入字符串时,正则表达式模式无法读取到三重引号的末尾。您知道如何将正则表达式更改为读取到三个刻度的末尾,而不在上断开吗\n?quoteMatcher.end()返回值2,因此下面的失败案例返回' 有效: '''<html><head></head></html>''' public static final Pattern QUOT
“'.*?'|'.*?”
模式查找三重引号(''')和单引号(')之间的文本。当回车被添加到输入字符串时,正则表达式模式无法读取到三重引号的末尾。您知道如何将正则表达式更改为读取到三个刻度的末尾,而不在上断开吗\n?quoteMatcher.end()返回值2,因此下面的失败案例返回'
有效:
'''<html><head></head></html>'''
public static final Pattern QUOTE_PATTERN = Pattern.compile("'''.*?'''|'.*?'");
Matcher quoteMatcher = QUOTE_PATTERN.matcher(value);
int normalPos = 0, length = value.length();
while (normalPos < length && quoteMatcher.find()) {
int quotePos = quoteMatcher.start(), quoteEnd = quoteMatcher.end();
if (normalPos < quotePos) {
copyBuilder.append(stripHTML(value.substring(normalPos, quotePos)));
}
//quoteEnd fails to read to the end due to \n
copyBuilder.append(value.substring(quotePos, quoteEnd));
normalPos = quoteEnd;
}
if (normalPos < length) copyBuilder.append(stripHTML(value.substring(normalPos)));
“'
失败:
'''<html><head></head></html>'''
public static final Pattern QUOTE_PATTERN = Pattern.compile("'''.*?'''|'.*?'");
Matcher quoteMatcher = QUOTE_PATTERN.matcher(value);
int normalPos = 0, length = value.length();
while (normalPos < length && quoteMatcher.find()) {
int quotePos = quoteMatcher.start(), quoteEnd = quoteMatcher.end();
if (normalPos < quotePos) {
copyBuilder.append(stripHTML(value.substring(normalPos, quotePos)));
}
//quoteEnd fails to read to the end due to \n
copyBuilder.append(value.substring(quotePos, quoteEnd));
normalPos = quoteEnd;
}
if (normalPos < length) copyBuilder.append(stripHTML(value.substring(normalPos)));
用户输入的值:
'''<html>
<head></head>
</html>'''
“”
'''
Java表示:
'''<html>\n<head></head>\n</html>'''
'''\n\n''
解析逻辑:
'''<html><head></head></html>'''
public static final Pattern QUOTE_PATTERN = Pattern.compile("'''.*?'''|'.*?'");
Matcher quoteMatcher = QUOTE_PATTERN.matcher(value);
int normalPos = 0, length = value.length();
while (normalPos < length && quoteMatcher.find()) {
int quotePos = quoteMatcher.start(), quoteEnd = quoteMatcher.end();
if (normalPos < quotePos) {
copyBuilder.append(stripHTML(value.substring(normalPos, quotePos)));
}
//quoteEnd fails to read to the end due to \n
copyBuilder.append(value.substring(quotePos, quoteEnd));
normalPos = quoteEnd;
}
if (normalPos < length) copyBuilder.append(stripHTML(value.substring(normalPos)));
publicstaticfinalpattern QUOTE_Pattern=Pattern.compile(“'.*?“'.'.*”);
匹配器quoteMatcher=QUOTE_PATTERN.Matcher(值);
int normalPos=0,length=value.length();
while(normalPos
只需使用模式.DOTALL
修饰符,使
也匹配换行符
public static final Pattern QUOTE_PATTERN = Pattern.compile("'''.*?'''|'.*?'", Pattern.DOTALL);
只需使用
模式.DOTALL
修饰符,这样
也会匹配换行符
public static final Pattern QUOTE_PATTERN = Pattern.compile("'''.*?'''|'.*?'", Pattern.DOTALL);
以及。