문자열에서 숫자를 추출하고 정수 배열을 얻는 방법은 무엇입니까?
문자열 변수 (기본적으로 숫자가 지정되지 않은 영어 문장)가 있고 모든 숫자를 정수 배열로 추출하고 싶습니다. 정규 표현식에 대한 빠른 솔루션이 있는지 궁금합니다.
Sean의 솔루션을 사용하고 약간 변경했습니다.
LinkedList<String> numbers = new LinkedList<String>();
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(line);
while (m.find()) {
numbers.add(m.group());
}
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}
... 인쇄 -2
및 12
.
-? 선행 음수 부호와 일치합니다. \ D는 숫자와 일치, 우리는 쓸 필요 \
로 \\
하지만 자바 문자열입니다. 따라서 \ d +는 하나 이상의 숫자와 일치합니다.
replaceAll
java.lang.String 메소드 를 사용하는 방법 :
String str = "qwerty-1qwerty-2 455 f0gfg 4";
str = str.replaceAll("[^-?0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
산출:
[-1, -2, 455, 0, 4]
기술
[^-?0-9]+
[
그리고]
하나의 임의의 순서로, 즉, 한 번만 일치하는 문자 집합을 delimites^
집합의 시작 부분에 사용되는 특수 식별자로 집합 에있는 모든 문자 대신 구분 된 집합에 없는 모든 문자를 일치시키는 데 사용됩니다 .+
한 번에서 무제한으로 가능한 한 많이, 필요에 따라 환원-?
"-"및 "?"문자 중 하나0-9
"0"에서 "9"사이의 문자
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(myString);
while (m.find()) {
int n = Integer.parseInt(m.group());
// append n to list
}
// convert list to array, etc
실제로 [0-9]를 \ d로 바꿀 수 있지만 이중 백 슬래시 이스케이프가 포함되어 읽기가 더 어렵습니다.
StringBuffer sBuffer = new StringBuffer();
Pattern p = Pattern.compile("[0-9]+.[0-9]*|[0-9]*.[0-9]+|[0-9]+");
Matcher m = p.matcher(str);
while (m.find()) {
sBuffer.append(m.group());
}
return sBuffer.toString();
소수를 유지하는 숫자를 추출하기위한 것입니다.
허용 된 대답은 숫자를 감지하지만 형식이 지정된 숫자 (예 : 2,000) 또는 소수 (예 : 4.8)는 감지하지 않습니다. 그러한 사용을 위해 -?\\d+(,\\d+)*?\\.?\\d+?
:
Pattern p = Pattern.compile("-?\\d+(,\\d+)*?\\.?\\d+?");
List<String> numbers = new ArrayList<String>();
Matcher m = p.matcher("Government has distributed 4.8 million textbooks to 2,000 schools");
while (m.find()) {
numbers.add(m.group());
}
System.out.println(numbers);
산출: [4.8, 2,000]
유리수의 경우 다음을 사용하십시오. (([0-9]+.[0-9]*)|([0-9]*.[0-9]+)|([0-9]+))
Java 8을 사용하여 다음을 수행 할 수 있습니다.
String str = "There 0 are 1 some -2-34 -numbers 567 here 890 .";
int[] ints = Arrays.stream(str.replaceAll("-", " -").split("[^-\\d]+"))
.filter(s -> !s.matches("-?"))
.mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(ints)); // prints [0, 1, -2, -34, 567, 890]
If you don't have negative numbers, you can get rid of the replaceAll
(and use !s.isEmpty()
in filter
), as that's only to properly split something like 2-34
(this can also be handled purely with regex in split
, but it's fairly complicated).
Arrays.stream
turns our String[]
into a Stream<String>
.
filter
gets rid of the leading and trailing empty strings as well as any -
that isn't part of a number.
mapToInt(Integer::parseInt).toArray()
calls parseInt
on each String
to give us an int[]
.
Alternatively, Java 9 has a Matcher.results method, which should allow for something like:
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There 0 are 1 some -2-34 -numbers 567 here 890 .");
int[] ints = m.results().map(MatchResults::group).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(ints)); // prints [0, 1, -2, -34, 567, 890]
As it stands, neither of these is a big improvement over just looping over the results with Pattern
/ Matcher
as shown in the other answers, but it should be simpler if you want to follow this up with more complex operations which are significantly simplified with the use of streams.
Extract all real numbers using this.
public static ArrayList<Double> extractNumbersInOrder(String str){
str+='a';
double[] returnArray = new double[]{};
ArrayList<Double> list = new ArrayList<Double>();
String singleNum="";
Boolean numStarted;
for(char c:str.toCharArray()){
if(isNumber(c)){
singleNum+=c;
} else {
if(!singleNum.equals("")){ //number ended
list.add(Double.valueOf(singleNum));
System.out.println(singleNum);
singleNum="";
}
}
}
return list;
}
public static boolean isNumber(char c){
if(Character.isDigit(c)||c=='-'||c=='+'||c=='.'){
return true;
} else {
return false;
}
}
Fraction and grouping characters for representing real numbers may differ between languages. The same real number could be written in very different ways depending on the language.
The number two million in German
2,000,000.00
and in English
2.000.000,00
A method to fully extract real numbers from a given string in a language agnostic way:
public List<BigDecimal> extractDecimals(final String s, final char fraction, final char grouping) {
List<BigDecimal> decimals = new ArrayList<BigDecimal>();
//Remove grouping character for easier regexp extraction
StringBuilder noGrouping = new StringBuilder();
int i = 0;
while(i >= 0 && i < s.length()) {
char c = s.charAt(i);
if(c == grouping) {
int prev = i-1, next = i+1;
boolean isValidGroupingChar =
prev >= 0 && Character.isDigit(s.charAt(prev)) &&
next < s.length() && Character.isDigit(s.charAt(next));
if(!isValidGroupingChar)
noGrouping.append(c);
i++;
} else {
noGrouping.append(c);
i++;
}
}
//the '.' character has to be escaped in regular expressions
String fractionRegex = fraction == POINT ? "\\." : String.valueOf(fraction);
Pattern p = Pattern.compile("-?(\\d+" + fractionRegex + "\\d+|\\d+)");
Matcher m = p.matcher(noGrouping);
while (m.find()) {
String match = m.group().replace(COMMA, POINT);
decimals.add(new BigDecimal(match));
}
return decimals;
}
If you want to exclude numbers that are contained within words, such as bar1 or aa1bb, then add word boundaries \b to any of the regex based answers. For example:
Pattern p = Pattern.compile("\\b-?\\d+\\b");
Matcher m = p.matcher("9There 9are more9 th9an -2 and less than 12 numbers here9");
while (m.find()) {
System.out.println(m.group());
}
displays:
2
12
I would suggest to check the ASCII values to extract numbers from a String Suppose you have an input String as myname12345 and if you want to just extract the numbers 12345 you can do so by first converting the String to Character Array then use the following pseudocode
for(int i=0; i < CharacterArray.length; i++)
{
if( a[i] >=48 && a[i] <= 58)
System.out.print(a[i]);
}
once the numbers are extracted append them to an array
Hope this helps
I found this expression simplest
String[] extractednums = msg.split("\\\\D++");
'Programming' 카테고리의 다른 글
SOAP 메시지와 WSDL의 차이점은 무엇입니까? (0) | 2020.08.15 |
---|---|
프로덕션에서 Rails 콘솔 실행 (0) | 2020.08.15 |
표준 C ++에서 모든 파일 / 디렉토리를 재귀 적으로 어떻게 반복합니까? (0) | 2020.08.15 |
jquery를 사용하지 않고 문서 높이와 너비를 얻는 방법 (0) | 2020.08.15 |
jquery를 사용하지 않고 문서 높이와 너비를 얻는 방법 (0) | 2020.08.15 |