------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------
정규식
[abc]
a, b, or c (simple class) -- a나 b나 c중의 하나
[^abc]
Any character except a, b, or c (negation) -- a나 b나 c만 아니면 된다.
[a-zA-Z]
a through z or A through Z, inclusive (range) -- 정규식은 대소문자를 구분한다.
[a-d[m-p]]
a through d, or m through p: [a-dm-p] (union) -- 위에 것과 같다 a~d 혹은 m~p의 값이 들어오면 참이다
[a-z&&[def]]
d, e, or f (intersection) -- 소문자 a~z까지 범위중 def중 하나와 같은것 이면 참이다. 즉 교집합과 같다.
[a-z&&[^bc]]
a through z, except for b and c: [ad-z] (subtraction) -- 소문자 a~z까지의 범위중 b나 c가 아니면 참이다
[a-z&&[^m-p]]
a through z, and not m through p: [a-lq-z](subtraction) -- 소문자 a~z까지의 범위중 m~p사의 것이 아니면 참이다.
.
Any character (may or may not match line terminators)
\d
A digit: [0-9] -- 0~9까지의 숫자 면 참
\D
A non-digit: [^0-9] -- 0~9의 숫자가 아닌것이면 참
\s
A whitespace character: [ \t\n\x0B\f\r]
\S
A non-whitespace character: [^\s]
\w
A word character: [a-zA-Z_0-9]
\W
A non-word character: [^\w]
while(cnt != 3){
String str = sc.next();
boolean boo = str.matches("1-9"); -- 1-9만 받아들인다 equals와 같아진다.
System.out.println(boo);
cnt++;
}
XY
X followed by Y
X|Y
Either X or Y
(X)
X, as a capturing group -- 괄호 사용시 하나의 묶음이 된다.
------------------------------------------------------------------------------------------------------------------------------------
ip주소 자바 정규식
public static final String IPV4_REGEX = "\\A(25[0-5]2[0-4]\\d[0-1]?\\d?\\d)(\\.(25[0-5]2[0-4]\\d[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_HEX4DECCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]2[0-4]\\d[0-1]?\\d?\\d)(\\.(25[0-5]2[0-4]\\d[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_6HEX4DEC_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]2[0-4]\\d[0-1]?\\d?\\d)(\\.(25[0-5]2[0-4]\\d[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_HEXCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z"; public static final String IPV6_REGEX = "\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z";
------------------------------------------------------------------------------------------------------------------------------------
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
<title>업로드 파일확장자 검사</title>
<script language=javascript>
function checkExt()
{
var IMG_FORMAT = "\\.(bmp|gif|jpg|jpeg|png)$";
if((new RegExp(IMG_FORMAT, "i")).test(document.form1.text1.value)) return true;
alert("이미지 파일만 첨부하실 수 있습니다. ");
return false;
}
</script>
</head>
<body>
<form name=form1 method=post onsubmit="return checkExt()"
encType="multipart/form-data">
<input type=file name=text1>
<input type=submit>
</form>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------
□ JSP
o 취약한 파일 업로드 예
<%@ page contentType="text/html;charset=euc-kr" %>
<%@ page import="com.oreilly.servlet.MultipartRequest,com.oreilly.servlet.multipart.DefaultFileRenamePolicy, java.util.*"%>
<%
String savePath="/var/www/uploads";// 업로드 디렉토리
int sizeLimit = 5 * 1024 * 1024 ;// 업로드 파일 사이즈 제한
try
MultipartRequest multi=new MultipartRequest(request, savePath, sizeLimit, new DefaultFileRenamePolicy());
Enumeration formNames=multi.getFileNames();// 폼의 이름 반환
String formName=(String)formNames.nextElement();
String fileName=multi.getFilesystemName(formName);// 파일의 이름 얻기
if(fileName == null)
out.print("Error");
else
fileName=new String(fileName.getBytes("8859_1"),"euc-kr");
out.print("User Name : " + multi.getParameter("userName") + "<BR>");
out.print("Form Name : " + formName + "<BR>");
out.print("File Name : " + fileName);
catch(Exception e)
out.print("Error");
%>
------------------------
o 안전한 파일 업로드 예
<%@ page contentType="text/html;charset=euc-kr" %>
<%@ page import="com.oreilly.servlet.MultipartRequest,com.oreilly.servlet.multipart.DefaultFileRenamePolicy, java.util.*"%>
<%
String savePath="/var/www/uploads";// 업로드 디렉토리
int sizeLimit = 5 * 1024 * 1024 ; // 업로드 파일 사이즈 제한
try
MultipartRequest multi=new MultipartRequest(request, savePath, sizeLimit, "euc-kr", new DefaultFileRenamePolicy());
Enumeration formNames=multi.getFileNames(); // 폼의 이름 반환
String formName=(String)formNames.nextElement();
String fileName=multi.getFilesystemName(formName); // 파일의 이름 얻기
String file_ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(!( file_ext.equalsIgnoreCase("hwp") || file_ext.equalsIgnoreCase("pdf") || file_ext.equalsIgnoreCase("jpg")) )
out.print("업로드 금지 파일");
if(fileName == null)
out.print("파일 업로드 실패");
else
fileName=new String(fileName.getBytes("8859_1"),"euc-kr"); // 한글인코딩
out.print("File Name : " + fileName);
catch(Exception e)
------------------------------------------------------------------------------------------------------------------------------------
download.jsp
<%@ page contentType="application;" %>
<%@ page language="java" import="java.util.*,java.io.*,java.sql.*,java.text.*" %>
<%@ include file="boardcfg.jsp" %>
<%
String mask = request.getParameter("mask");
String fileP = request.getRealPath("/")+"upload/";
String fileN1 = "", fileN2 = "";
long fSize = 0;
String queryw = " WHERE maskname = ? ";
String query = "SELECT filename, filesize from "+tableName+" " + queryw;
String query2 = "update "+tableName+" SET download = download + 1 " + queryw;
Connection pconn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
%>
<%@ include file = "db.jsp"%>
<%
pstmt = pconn.prepareStatement(query);
pstmt.setString(1,mask);
rs = pstmt.executeQuery();
if(rs.next()) {
fileN1 = mask;
fileN2 = rs.getString("filename");
fileN2 = new String(fileN2.getBytes("euc-kr"),"8859_1");
fSize = rs.getInt("filesize");
}
rs.close();
pstmt.clearParameters();
pstmt = pconn.prepareStatement(query2);
pstmt.setString(1,mask);
pstmt.executeUpdate();
pstmt.close();
} catch(Exception e){
} finally {
if (pstmt!=null) pstmt.close();
if (pconn!=null) pconn.close();
}
// Download file
String ut = fileP+fileN1;
File file = new File(ut); // 절대경로입니다.
byte b[] = new byte[(int)file.length()];
String strClient=request.getHeader("User-Agent");
if(strClient.indexOf("MSIE 5.5")>-1) {
response.setHeader("Content-Disposition", "filename=" + fileN2 + ";");
} else {
response.setHeader("Content-Disposition", "attachment;filename=" + fileN2 + ";");
}
if (fSize > 0 && file.isFile())
{
BufferedInputStream fin = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
int read = 0;
try {
while ((read = fin.read(b)) != -1){
outs.write(b,0,read);
}
outs.close();
fin.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if(outs!=null) outs.close();
if(fin!=null) fin.close();
}
}
%>
------------------------------------------------------------------------------------------------------------------------------------
'JAVA > Regular Expression' 카테고리의 다른 글
replaceAll 정규식 팁! (0) | 2013.03.22 |
---|---|
Java 정규 표현식 사용하기 (0) | 2013.03.06 |