Reputation: 29
How to create a method which will find a number in String Text. I contain List of Strings which contain text like:
Radius of Circle is 7 cm
Rectangle 8 Height is 10 cm
Rectangle Width is 100 cm, Some text
Now I have to find all the number in these lines which are coming before cm so that I don't mistakenly find any other number.
How can it happen
Upvotes: 0
Views: 891
Reputation: 522396
The correct pattern to use here is:
(\\d+)\\s+cm\\b
For a one liner, we can try using String#replaceAll
:
String input = "Rectangle Width is 100 cm, Some text";
String output = input.replaceAll(".*?(\\d+)\\s+cm\\b.*", "$1");
System.out.println(output);
Or, to find all matches in a given text, we can try using a formal pattern matcher:
String input = "Rectangle Width is 100 cm, Some text";
String pattern = "(\\d+)\\s+cm\\b";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
System.out.println("Found measurement: " + m.group(1));
}
Upvotes: 1
Reputation: 1997
You have to find groups with only digits in the string using the following regex:
(?:\d{1,})
import java.util.regex.Pattern;
import java.util.Scanner;
import java.util.regex.Matcher;
public class RegexExample{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while (true) {
Pattern pattern = Pattern.compile("(?:\\d{1,})");
System.out.println("Enter text:");
Matcher matcher = pattern.matcher(sc.nextLine());
boolean found = false;
while (matcher.find()) {
System.out.println("I found the text "+matcher.group()+" starting at index "+
matcher.start()+" and ending at index "+matcher.end());
found = true;
}
if(!found){
System.out.println("No match found.");
}
}
}
}
Enter text:
Radius of Circle is 7 cm
I found the text 7 starting at index 20 and ending at index 21
Enter text:
Rectangle 8 Height is 10 cm
I found the text 8 starting at index 10 and ending at index 11
I found the text 10 starting at index 22 and ending at index 24
Enter text:
Rectangle Width is 100 cm, Some text
I found the text 100 starting at index 19 and ending at index 22
Enter text:
Note: In java code, the character \
it's an escape character. That's why you have to append another \
.
Upvotes: 1
Reputation: 3949
A matching regular expression would be:
(\d+) cm
In order to obtain the captured number before the cm
, you can use the Pattern
and Matcher
classes:
String line = "Radius of Circle is 7 cm";
Pattern pattern = Pattern.compile("(\\d+) cm");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println("Value: " + matcher.group(1));
}
This example only matches the line from example (1), but can be easily repeated for each the lines contained in your list. See Java Regex Capture Groups for more information.
Upvotes: 2