문자열에서 정수 부분을 추출합니다
-
19-09-2019 - |
문제
문자열의 정수 부분을 추출하는 가장 좋은 방법은 무엇입니까?
Hello123
123 부품을 어떻게 얻습니까? Java의 스캐너를 사용하여 해킹 할 수 있습니다. 더 좋은 방법이 있습니까?
해결책
원하는 문자열 부분과 일치하기 위해 정규 표현식을 사용하지 않는 이유는 무엇입니까?
[0-9]
그것이 당신이 필요한 전부와 주변 숯이 필요한 모든 것입니다.
보다 http://www.regular-expressions.info/tutorial.html 정규 표현이 어떻게 작동하는지 이해합니다.
편집 : 다른 제출자가 게시 한 코드가 작품을 게시 한 경우,이 예제에 대해 Regex가 약간 오버 배가 될 수 있다고 말하고 싶습니다. 그러나 여전히 REGEX를 배우는 것이 좋습니다. 내가 인정하고 싶은 것보다 더 편리하게 올 것입니다 (몇 년을 기다린 후에 샷을주기 전에).
다른 팁
이전에 설명했듯이 정규 표현식을 사용해보십시오. 이것은 도움이 될 것입니다 :
String value = "Hello123";
String intValue = value.replaceAll("[^0-9]", ""); // returns 123
그리고 당신은 그것을 거기에서 int (또는 정수)로 변환합니다.
나는 당신이 다음과 같이 할 수 있다고 생각합니다.
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
편집 : Carlos에 의해 사용 된 Eldimiter 제안을 추가했습니다
후행 숫자를 원한다고 가정하면 다음과 같습니다.
import java.util.regex.*;
public class Example {
public static void main(String[] args) {
Pattern regex = Pattern.compile("\\D*(\\d*)");
String input = "Hello123";
Matcher matcher = regex.matcher(input);
if (matcher.matches() && matcher.groupCount() == 1) {
String digitStr = matcher.group(1);
Integer digit = Integer.parseInt(digitStr);
System.out.println(digit);
}
System.out.println("done.");
}
}
나는 Michael의 Regex가 가능한 가장 간단한 솔루션이라고 생각했지만, 두 번째 생각에서 " d+"는 matcher.matches () : matches () 대신 matcher.find ()를 사용하면 작품입니다.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Example {
public static void main(String[] args) {
String input = "Hello123";
int output = extractInt(input);
System.out.println("input [" + input + "], output [" + output + "]");
}
//
// Parses first group of consecutive digits found into an int.
//
public static int extractInt(String str) {
Matcher matcher = Pattern.compile("\\d+").matcher(str);
if (!matcher.find())
throw new NumberFormatException("For input string [" + str + "]");
return Integer.parseInt(matcher.group());
}
}
나는 그것이 6 살짜리 질문이라는 것을 알고 있지만, 지금 Regex를 배우지 않으려는 사람들에게 답을 게시하고 있습니다 (BTW). 이 접근법은 또한 숫자 사이의 숫자를 제공합니다 (예 : HP123kt567 123567로 돌아갑니다)
Scanner scan = new Scanner(new InputStreamReader(System.in));
System.out.print("Enter alphaNumeric: ");
String x = scan.next();
String numStr = "";
int num;
for (int i = 0; i < x.length(); i++) {
char charCheck = x.charAt(i);
if(Character.isDigit(charCheck)) {
numStr += charCheck;
}
}
num = Integer.parseInt(numStr);
System.out.println("The extracted number is: " + num);
String[] parts = s.split("\\D+"); //s is string containing integers
int[] a;
a = new int[parts.length];
for(int i=0; i<parts.length; i++){
a[i]= Integer.parseInt(parts[i]);
System.out.println(a[i]);
}