> Java > java지도 시간 > 본문

Java의 교체All()

王林
풀어 주다: 2024-08-30 15:38:10
원래의
711명이 탐색했습니다.

ReplaceAll()은 매개 변수와 일치하는 모든 문자를 바꾸는 String 클래스의 메서드입니다. 모든 하위 문자열은 정규 표현식으로 메서드에 전달한 입력으로 대체되고 주어진 문자열을 대체합니다. 이 메소드를 시작하면 String 객체가 반환됩니다. 이는 이 패키지의 String 클래스(java.lang.String) 내에 있습니다. 이번 주제에서는 Java의 replacementAll()에 대해 알아보겠습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

매개변수 구문

공용 문자열 교체All(문자열 정규식, 문자열 교체)

위는 replacementAll() 메소드에 대한 메소드 서명입니다. String 클래스에서 제공하는 java in build 메소드로 인해 코드에서 직접 사용할 수 있습니다. 두 개의 매개변수를 입력으로 사용합니다.

  • regex(정규 표현식): 이 입력은 주어진 문자열을 일치시키는 데 사용됩니다.
  • replacement : 위에서 일치하는 문자열 위치에 원하는 문자열로 사용됩니다. 이는 출력으로 보고자 하는 새로운 콘텐츠 또는 문자열입니다.

이 메서드는 항상 문자열 개체를 반환합니다. 한 가지 더, 정규 표현식도 패턴을 사용하는데, 이에 대해서는 아래에서 논의하겠습니다.

결과 문자열: 출력으로

Java에서 replacementAll() 메소드는 어떻게 작동하나요?

replaceAll은 String 클래스에 존재하는 메소드입니다. 입력으로 두 개의 매개변수, 즉 정규식과 대체를 사용합니다. 이름에서 알 수 있듯이 문자열의 일부 또는 전체를 대체하는 데 사용됩니다.

이 메서드는 아래에 언급된 예외를 발생시킵니다.

1. 패턴구문예외

이 예외는 입력 매개변수로 메서드에 전달한 정규식에 오류가 있는 경우에만 발생하는 java의 확인되지 않은 예외입니다. 다른 클래스와 마찬가지로 문제를 식별하는 데 도움이 되는 사전 정의된 메서드나 빌드 내 메서드가 있습니다.

  • public String getMessage(): 이 메소드에는 예외에 대한 설명이 포함되어 있습니다.
  • public int getIndex(): 이 메소드는 오류에 대한 색인을 반환합니다.
  • public String getPattern(): 이 메소드는 오류가 포함된 정규식을 제공합니다.
  • public String getDescription(): 이 메소드는 오류와 관련된 암호 해독을 제공합니다.

2. 정규식 세부정보

메서드 매개변수에 문자열로 전달하는 정규식이지만 이 정규식은 패턴 클래스의 컴파일된 인스턴스입니다. java.util.regex.Pattern 패키지에 있습니다.

이 정규식에는 다음 내용이 포함되어 있습니다.

  • 패턴
  • 매처

여기에는 matcher 메서드도 있습니다. 정규 표현식을 준수합니다.

  • t: 탭용
  • a: 경고용
  • cx: 제어 문자
  • e: 이스케이프 문자
  • n: 개행
  • f: 용지 공급

3. 사용 가능한 방법

  • split(CharSequence 입력): 이 메소드는 string[](문자열 배열)을 반환하고 분할하려는 대신 입력을 받습니다.
  • split(CharSequence input, intlimit): 동일한 방식으로 작동하지만 이 메서드도 제한 매개변수를 사용합니다.
  • 정적 패턴 컴파일(문자열 정규식, int 플래그): 이 방법은 정규식과 플래그라는 두 개의 매개변수를 사용하여 정규식을 컴파일합니다.
  • 4) 문자열 패턴()
  • 5) 정적 문자열 인용(String s)

이 패턴 클래스는 직렬화 가능 인터페이스도 구현합니다.

이런 식으로 교체All은 Java에서 작동합니다. 내부적으로 패턴과 일치 항목을 사용하여 정규식을 컴파일하고 기타 작업을 수행합니다.

Java의 replacementAll() 예

다음은 이를 사용하여 단일 문자, 정규식과 일치하는 전체 문자열을 바꾸고, 전체 문자열에서 공백을 제거하고, 문자열을 특수 문자로 바꾸는 방법을 보여주는 몇 가지 예입니다.

예시 #1

이 예에서는 정규식을 (.*)java(.*) this로 전달하여 부분 문자열이 시작과 끝에서 java인 전체 문자열을 바꿉니다.

코드:

import java.io.*;
public class DemoReg {
public static void main(String args[]) {
String str = new String("Example to show replace in java string.");
System.out.print("Resulted string after replace is  :" );
System.out.println(str.replaceAll("(.*)java(.*)", "replaced"));
}
}
로그인 후 복사

출력:

Java의 교체All()

예시 #2

이 예에서는 문자열 부분을 특수 문자로 대체합니다. 이는 문자열로 처리할 수 있는 모든 항목을 전달할 수 있음을 의미합니다. 숫자도 전달할 수 있습니다.

코드:

public class DemoReg {
public static void main(String args[]) {
String s1="In this we are going to replace the string with some character. (repeat sequence)";
String str=s1.replaceAll("t*"," ***** ");
System.out.println("Ouptut is ::: ");
System.out.println(str);
}
}
로그인 후 복사

출력:

Java의 교체All()

Example #3

In this java class, we are replacing some part of the string with some other content. Example: “replacement done successfully” this in our case.

Code:

public class DemoReg {
public static void main(String args[]) {
String str="Now the demo is for replacing string with some another substring";
String result=str.replaceAll("string"," replacement done successfully");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}
로그인 후 복사

Output:

Java의 교체All()

Example #4

In this example, we are trying to remove the spaces which are present in the given string. We have so many keywords with slashes (“\\”) that can be used to perform the given string’s operation.

Code:

public class DemoReg {
public static void main(String args[]) {
String str="Now we are going to replace the spaces present in the given string.";
System.out.println("String before replace performed :::: ");
System.out.println(str);
String result=str.replaceAll("\\s","");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}
로그인 후 복사

Output:

Java의 교체All()

Example #5

In this java example, we are replacing the string with a single character only. It means when the given character appears in the string each time, it will be replaced by the method.

Code:

public class DemoReg {
public static void main(String args[]) {
String str="Replacing single character from the whole string demo.";
System.out.println("String before replace performed :::: ");
System.out.println(str);
String result=str.replaceAll("e"," X");
System.out.println("Result after replace is :::: ");
System.out.println(result);
}
}
로그인 후 복사

Output:

Java의 교체All()

We can have anything in the replacement, which is a string. But our regular expression has to be valid; otherwise, it will throw an unchecked exception for error containing regular expression in the replaceAll() method.

Conclusion

Replace method is the string class method of java, which takes two parameters. Any type of regular expression we can pass in it will replace the string for us unless it matches. So the above example will give you an understanding that how we can use this.

위 내용은 Java의 교체All()의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!