"ali123hgj"와 같은 것을 가지고 있습니다. 나는 정수 123을 원한다. 어떻게 내가 자바로 만들 수 있을까?숫자가 Java 문자열에 없습니다.
7
A
답변
8
다음 정규식을 사용하여 (http://java.sun.com/docs/books/tutorial/essential/regex/ 참조)
\d+
작성자 :
final Pattern pattern = Pattern.compile("\\d+"); // the regex
final Matcher matcher = pattern.matcher("ali123hgj"); // your string
final ArrayList<Integer> ints = new ArrayList<Integer>(); // results
while (matcher.find()) { // for each match
ints.add(Integer.parseInt(matcher.group())); // convert to int
}
11
int i = Integer.parseInt("blah123yeah4yeah".replaceAll("\\D", ""));
// i == 1234
참고이 함께 하나 개의 번호로 문자열의 다른 부분에서 숫자를 "병합"하는 방법 . 어쨌든 번호가 하나뿐이라면 여전히 작동합니다. 정규식은 좀 더 복잡하다
int i = Integer.parseInt("x-42x100x".replaceAll("^\\D*?(-?\\d+).*$", "$1"));
// i == -42
하지만, 기본적으로 옵션으로 (이 포함 숫자의 첫 번째 순서로 전체 문자열을 대체 당신은 첫 번째 번호를 원하는 경우에, 당신은 이런 식으로 뭔가를 할 수 빼기 부호), Integer.parseInt
을 사용하여 정수로 파싱합니다.
0
당신은 아마 이러한 라인을 따라 그것을 할 수 :
는Pattern pattern = Pattern.compile("[^0-9]*([0-9]*)[^0-9]*");
Matcher matcher = pattern.matcher("ali123hgj");
boolean matchFound = matcher.find();
if (matchFound) {
System.out.println(Integer.parseInt(matcher.group(0)));
}
그것은뿐만 아니라 여러 숫자 그룹에 쉽게 적응할 수 있습니다. 이 코드는 오리엔테이션을위한 것일 뿐이므로 테스트되지 않았습니다.
0
int index = -1;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i)) {
index = i; // found a digit
break;
}
}
if (index >= 0) {
int value = String.parseInt(str.substring(index)); // parseInt ignores anything after the number
} else {
// doesn't contain int...
}
0
public static final List<Integer> scanIntegers2(final String source) {
final ArrayList<Integer> result = new ArrayList<Integer>();
// in real life define this as a static member of the class.
// defining integers -123, 12 etc as matches.
final Pattern integerPattern = Pattern.compile("(\\-?\\d+)");
final Matcher matched = integerPattern.matcher(source);
while (matched.find()) {
result.add(Integer.valueOf(matched.group()));
}
return result;
입력 "asg123d의 ddhd-2222-33sds --- --- 222 개 --- 234 SS 33dd"이 OUPUT 결과 [123 -2222, -33, -222, - 33, 234]
1
이것은 Google Guava #CharMatcher 웨이입니다.
만 ASCII 숫자와 일치하도록 신경 경우
, 당신은 단지 라틴 알파벳의 문자와 일치하도록 신경 경우String alphanumeric = "12ABC34def"; String digits = CharMatcher.JAVA_DIGIT.retainFrom(alphanumeric); // 1234 String letters = CharMatcher.JAVA_LETTER.retainFrom(alphanumeric); // ABCdef
String digits = CharMatcher.inRange('0', '9').retainFrom(alphanumeric); // 1234
을 사용하여 사용
String letters = CharMatcher.inRange('a', 'z')
.or(inRange('A', 'Z')).retainFrom(alphanumeric); // ABCdef
관련 문제
- 1. 문자열에 숫자가 포함되어 있는지 확인
- 2. 문자열에 숫자가 포함되어 있는지 감지하는 방법은 무엇입니까?
- 3. Java DecimalFormat 왼쪽에있는 모든 숫자가
- 4. UrlRewriting.Net 정규식 - "문자열에 없습니다"
- 5. 문자열에 정수보다 작은 숫자가 포함되어 있는지 어떻게 확인할 수 있습니까?
- 6. Ruby를 사용하여 문자열에 숫자가 하나 이상 있는지 어떻게 확인합니까?
- 7. 숫자가
- 8. 사용자 입력을 JAVA 문자열에 저장
- 9. Java : 문자열 [] 배열 요소를 문자열에 할당 하시겠습니까?
- 10. 문자열에 대한 Java enums vs 상수
- 11. Java indexOf가 원인이없는 문자열에 대해 false를 반환합니까?
- 12. 특수 문자열이 Java 문자열에 있는지 찾는 방법
- 13. Java 문자열에 불필요한 데이터가 포함되어 있습니다.
- 14. Java 정규 표현식을 사용하여 숫자가 아닌 숫자가 아닌 문자열을 식별 할 수 있습니다.
- 15. NSMutableArray에 저장된 문자열에 componentsSeparatedByString을 사용할 수 없습니다.
- 16. 모든 숫자가 같은지 확인하십시오.
- 17. 문자열에
- 18. []() 문자열에
- 19. 사용자 입력을 기반으로 숫자가 발생하는 것을 표시합니다. 배열, java
- 20. 정규식 자바 문자열에
- 21. 숫자가 적은 배열로보기?
- 22. 숫자가 거꾸로 표시됩니까?
- 23. BackgroundWorker 스레드의 숫자가 맞습니까?
- 24. 숫자가 완전하거나 소수인지를 결정하십시오.
- 25. 파이썬에서 숫자가 합리적인지 확인
- 26. 숫자가 아닌 인덱스의 성능
- 27. 숫자가 증가하지 않을 것입니다.
- 28. 숫자가 내림차순으로 오름차순
- 29. URL에 숫자가 아닌 문자
- 30. 하나의 올을위한 숫자가 없음
''abc123def567ghi ''또는''abcdef''는 어떨까요? – kennytm
숫자 앞에 항상 3 개의 문자가 있거나 그냥 예일뿐입니다? – lbedogni
3 문자 만이 아닙니다. 0 개 이상의 문자 사이의 숫자입니다. "123", "sdfs", "123fdhf", "fgdkjhgf123" –