2021.05.11
정규표현식
public class Ex81_RegEx {
public static void main(String[] args) {
String txt = "안녕하세요. 홍길동입니다. 제 전화번호는 010-1234-5678입니다. 그리고 집 전화는 02-987-6543입니다. 연락주세요.";
System.out.println(txt.replaceAll("[0-9]{2,3}-[0-9]{3,4}-[0-9]{4}", "XXX-XXXX-XXXX"));
String name = "홍길동,아무개.하하하,호호호.후후후";
String[] result = name.split("[,\\.]");
for(int i=0; i<result.length; i++) {
System.out.printf("resuslt[%d] = %s\n", i, result[i]);
}
}
}
public class Ex81_RegEx {
public static void main(String[] args) {
String txt = "안녕하세요. 홍길동입니다. 제 전화번호는 010-1234-5678입니다. 그리고 집 전화는 02-987-6543입니다. 연락주세요.";
Pattern p = Pattern.compile("\\d{2,3}-\\d{3,4}-\\d{4}");
Matcher m = p.matcher(txt);
if(m.find()) {
System.out.println("게시물 작성 금지!!");
System.out.println(m.group());
} else {
System.out.println("게시물 작성 완료~");
}
txt = "글을 쓰고 있습니다...바보";
p = Pattern.compile("(바보|멍청이)");
m = p.matcher(txt);
if(m.find()) {
System.out.println("금지어 사용!!");
System.out.println(m.group());
} else {
System.out.println("통과~~");
}
txt = "안녕하세요. 제 몸무게는 75kg입니다. 키는 175cm입니다. 나이는 20살입니다.";
p = Pattern.compile("\\d{1,}");
m = p.matcher(txt);
while (m.find()) {
System.out.println(m.group());
}
}
}
public class Ex81_RegEx {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("dat\\naver.txt"));
String wholeText = "";
String line = "";
while((line = reader.readLine()) != null) {
wholeText += line + "\r\n";
}
reader.close();
Pattern p = Pattern.compile("(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?");
Matcher m = p.matcher(wholeText);
while(m.find()) {
System.out.println(m.group());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
public class Ex81_RegEx {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("나이 입력: ");
String input = scan.nextLine();
String regex = "^[0-3]{1,3}$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if(m.find()) {
System.out.println("올바른 나이를 입력함");
} else {
System.out.println("나이는 숫자로 작성할 것!!");
}
}
}
public class Ex81_RegEx {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("아이디 입력: ");
String input = scan.nextLine();
String regex = "^[A-Za-z_]\\w{3,11}$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if(m.find()) {
System.out.println("통과");
} else {
System.out.println("실패");
}
}
}
public class Ex81_RegEx {
public static void main(String[] args) {
String txt = "안녕하세요. 홍길동입니다. 제 전화번호는 010-1234-5678입니다. 그리고 집 전화는 02-987-6543입니다. 연락주세요.";
Pattern p = Pattern.compile("\\d{2,3}-(\\d{3,4})-(\\d{4})");
Matcher m = p.matcher(txt);
while(m.find()) {
System.out.println(m.group());
System.out.println(m.group(1));
System.out.println(m.group(2));
}
}
}