문자열에서 특수 문자를 바꾸는 방법은 무엇입니까?
특수 문자가 많은 문자열이 있습니다. 나는 그것들을 모두 제거하고 싶지만 알파벳 문자는 유지합니다.
어떻게 할 수 있습니까?
그것은 당신이 의미하는 바에 달려 있습니다. 그것들을 제거하고 싶다면 다음과 같이하십시오 :
(업데이트 : 분명히 숫자도 유지하고 싶다면 두 번째 줄을 사용하십시오)
String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");
또는 이에 상응하는 것 :
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
(이 모든 것은 정규식 패턴을 미리 컴파일하고 상수에 저장하여 크게 향상시킬 수 있습니다)
또는 Guava를 사용하여 :
private static final CharMatcher ALNUM =
CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);
그러나 악센트 부호가있는 문자를 여전히 ascii 인 합리적인 것으로 바꾸려면 다음 질문을 살펴보십시오.
나는 이것을 사용하고있다.
s = s.replaceAll("\\W", "");
문자열의 모든 특수 문자를 대체합니다.
여기
\ w : 단어 문자, [a-zA-Z_0-9]의 약자
\ W : 단어가 아닌 문자
다음 방법을 사용하여 영숫자를 유지할 수 있습니다.
replaceAll("[^a-zA-Z0-9]", "");
그리고 알파벳 문자 만 유지하려면 이것을 사용하십시오.
replaceAll("[^a-zA-Z]", "");
string Output = Regex.Replace(Input, @"([ a-zA-Z0-9&, _]|^\s)", "");
여기서 공백, 쉼표 및 앰퍼샌드를 제외한 모든 특수 문자가 대체됩니다. 다음 정규식으로 공백, 쉼표 및 앰퍼샌드를 생략 할 수도 있습니다.
string Output = Regex.Replace(Input, @"([ a-zA-Z0-9_]|^\s)", "");
여기서 Input은 문자를 대체하는 데 필요한 문자열입니다.
특수 문자를
replaceAll("\\your special character","new character");
예 : *의 모든 항목을 공백으로 바꾸려면
replaceAll("\\*","");
*이 문장은 한 번에 한 가지 유형의 특수 문자 만 대체 할 수 있습니다.
Andrzej Doyle의 답변 예에 따라 더 나은 해결책은 다음을 사용하는 것입니다 org.apache.commons.lang3.StringUtils.stripAccents()
.
package bla.bla.utility;
import org.apache.commons.lang3.StringUtils;
public class UriUtility {
public static String normalizeUri(String s) {
String r = StringUtils.stripAccents(s);
r = r.replace(" ", "_");
r = r.replaceAll("[^\\.A-Za-z0-9_]", "");
return r;
}
}
You can use basic regular expressions on strings to find all special characters or use pattern and matcher classes to search/modify/delete user defined strings. This link has some simple and easy to understand examples for regular expressions: http://www.vogella.de/articles/JavaRegularExpressions/article.html
You can get unicode for that junk character from charactermap tool in window pc and add \u e.g. \u00a9 for copyright symbol. Now you can use that string with that particular junk caharacter, don't remove any junk character but replace with proper unicode.
For spaces use "[^a-z A-Z 0-9]" this pattern
참고URL : https://stackoverflow.com/questions/4283351/how-to-replace-special-characters-in-a-string
'development' 카테고리의 다른 글
Android에서 뷰를 애니메이션하고 새 위치 / 크기를 유지하려면 어떻게해야합니까? (0) | 2020.10.06 |
---|---|
Linq OrderBy 인수를 어떻게 동적으로 지정합니까? (0) | 2020.10.06 |
“0”과“1”을 거짓과 참으로 변환하는 방법 (0) | 2020.10.06 |
UITapGestureRecognizer는 self.view를 탭하지만 하위보기는 무시합니다. (0) | 2020.10.06 |
Node.js의 백그라운드 프로세스 (0) | 2020.10.05 |