I have a string like
> 12.4N-m/kg.
From the above string I need to get a value 12.4.
When I use replace all function str.replaceAll("[^.0-9]", "").
This doesn't work when then string has two dots.
The location of float value may differ.
First discard all non flot characters and then covert to Float like this:
float f = Float.valueOf("> 12.4N-m/kg.".replaceAll("[^\\d.]+|\\.(?!\\d)", ""));
// now f = 12.4
Assuming your input always has a space before the number and an N after it:
String t = "> 12.4N-m/kg.";
Pattern p = Pattern.compile("^.*\\s(\\d+\\.\\d)N.*$");
Matcher matcher = p.matcher(t);
if (matcher.matches()) {
System.out.println(Float.valueOf(matcher.group(1)));
}
Try to use this:
Float.valueOf(str.substring(0,4));
following code will work with assumption that input string always starts with "> " and it has proper float prefixed.
int i=2;
while(Character.isDigit(str.charAt(i)) || str.charAt(i) == '.')
i++;
float answer = Float.valueOf(str.substring(2,i));
Try to use this regular expression
^[-+]?[0-9]*\.?[0-9]+$
I think the previous answers leave out two points:
There are more complicated numbers than this.
There might be a digit in the unit which souldn't end up in the float.
Because of the second point I don't think replacing everything that is a non-digit is a good idea. One should rather search for the first number in the string:
Matcher m = p.matcher(str);
System.out.println("Input: "+ str);
if (m.find()) {
System.out.println("Found: "+ m.group());
try {
System.out.println("Number: "+ Float.parseFloat(m.group()));
} catch (Exception exc) {
exc.printStackTrace();
}
}
Alternatively, you could do something like
int i, j;
for (i = 0; i < str.length(); ++i) {
if (mightBePartOfNumber(str.charAt(i))) {
break;
}
}
for (j = i; j < str.length(); ++j) {
if (!mightBePartOfNumber(str.charAt(j))) {
break;
}
}
String substr = str.substring(i, j);
System.out.println("Found: "+ substr);
try {
System.out.println("Number: "+ Float.parseFloat(substr));
} catch (Exception exc) {
exc.printStackTrace();
}
with a helper
private static boolean mightBePartOfNumber(char c) {
return ('0' <= c && c <= '9') || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E';
}
I have tried the above options but not worked for me , Please try below pattern
Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?");
Related
This question already has an answer here:
Match contents within square brackets, including nested square brackets
(1 answer)
Closed 3 years ago.
I want to extract the string content inside square brackets (if inside one square brackets contains nested square brackets, it should be ignored).
Example:
c[ts[0],99:99,99:99] + 5 - d[ts[1],99:99,99:99, ts[2]] + 5
Should return:
match1 = "ts[0],99:99,99:99";
match2 = "ts[1],99:99,99:99, ts[2]";
The code I have so far works only with non-nested square brackets
String in = "c[ts[0],99:99,99:99] + 5 - d[ts[1],99:99,99:99, ts[2]] + 5";
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(in);
while(m.find()) {
System.out.println(m.group(1));
}
// print: ts[0, ts[1, 2
I made a function to do it (not with regex, but it works)
for (int i = 0; i < in.length(); i++){
char c = in.charAt(i);
String part = String.valueOf(c);
int numberOfOpenBrackets = 0;
if (c == '[') {
part = "";
numberOfOpenBrackets++;
for (int j = i + 1; j < in.length(); j++) {
char d = in.charAt(j);
if (d == '[') {
numberOfOpenBrackets++;
}
if (d == ']') {
numberOfOpenBrackets--;
i = j;
if (numberOfOpenBrackets == 0) {
break;
}
}
part += d;
}
System.out.println(part);
part = "[" + part + "]";
}
result += part;
}
// print: ts[0],99:99,99:99
// ts[1],99:99,99:99, ts[2]
If the nesting is just one level, you can search for a sequence between the brackets:
a sequence of:
either a not a [
or a [ followed by the shortest sequence to ]
So
Pattern p = Pattern.compile("\\[([^\\[]|\\[.*?\\])*\\]");
// [ ]
// ( not-[ or
// [, shortest sequence to ]
// )* repeatedly
The problem being that brackets must be correctly paired: no syntax errors allowed.
Without regex; just straight java:
import java.util.ArrayList;
import java.util.List;
public class BracketParser {
public static List<String> parse(String target) throws Exception {
List<String> results = new ArrayList<>();
for (int idx = 0; idx < target.length(); idx++) {
if (target.charAt(idx) == '[') {
String result = readResult(target, idx + 1);
if (result == null) throw new Exception();
results.add(result);
idx += result.length() + 1;
}
}
return results;
}
private static String readResult(String target, int startIdx) {
int openBrackets = 0;
for (int idx = startIdx; idx < target.length(); idx++) {
char c = target.charAt(idx);
if (openBrackets == 0 && c == ']')
return target.substring(startIdx, idx);
if (c == '[') openBrackets++;
if (c == ']') openBrackets--;
}
return null;
}
public static void main(String[] args) throws Exception {
System.out.println(parse("c[ts[0],99:99,99:99] + 5 - d[ts[1],99:99,99:99, ts[2]] + 5"));
}
}
Complete code on GitHub
You might want to add a right boundary in your expression and ts start and swipe everything in between, which might work, maybe similar to this expression:
(ts.*?)(\]\s+\+)
If we have more chars here: (\s\+), you can simply add it with logical ORs in a char list and it would still work.
RegEx
If this wasn't your desired expression, you can modify/change your expressions in regex101.com.
RegEx Circuit
You can also visualize your expressions in jex.im:
Now,if I have a String like this:
String start = "(1374)(48.4%)(32)(100%)(290)(43.1%)";
How can I extract the six numbers 1374 48.4 32 100 290 43.1 or 1374 48.4% 32 100% 290 43.1%? Can it be done with a regex?
You can search for a regex identifying floating point numbers: ([+-]?(\d+\.)?\d+)
String start = "(1374)(48.4%)(32)(100%)(290)(43.1%)";
Pattern p = Pattern.compile("([+-]?(\\d+\\.)?\\d+)");
Matcher m = p.matcher(start);
while (m.find()) {
System.out.println(m.group(1));
}
Or use a regex that also makes sure that the brackets are there:
Pattern p = Pattern.compile("\\(([+-]?(\\d+\\.)?\\d+)\\%?\\)");
Let's do it without a regex!
int i = 0;
while (i < start.length()) {
while (i < start.length()) {
char ch = start.charAt(i);
// Maybe add other characters, e.g. %, if desired.
if (Character.isDigit(ch) || ch == '.') {
break;
}
++i;
}
int startOfBlock = i;
while (i < start.length()) {
char ch = start.charAt(i);
if (!Character.isDigit(ch) && ch != '.') {
break;
}
++i;
}
if (i > startOfBlock) {
System.out.println(start.substring(startOfBlock, i));
}
}
or u can try the following regex [\d\.%]+ it gives u the combinations of the strings containing the following items \d (digit) \. dot and % procentage sign one or more times click here for a live demo
String start = "(1374)(48.4%)(32)(100%)(290)(43.1%)";
for(String splitString : start.split("[()]")) {
System.out.print(splitString + " ");
}
I am learning regular expression.Suppose, If I have two String like abcd & bcdd. To make them equal Strings I have to remove a from first and d from last string. is this possible to count the matched number like bcd=> (3).
Currently, I am doing this
Pattern p= Pattern.compile("["+abcd+"]{2}");
Matcher m= p.matcher("abcd bcdd");
My current solution doesn't provide me the correct result. So, my question
1) Is this possible ?
2) If possible, then how can I achieve that ?
Hope, you will help to increase my regular expression knowledge.
Not sure why you would use regex at all, if all you need is the number of "bcd"s. I've put both a non-regex and regex version here for comparison.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
<P>{#code java BcdRegexXmpl}</P>
**/
public class BcdRegexXmpl {
public static final void main(String[] igno_red) {
String sSentence = "abcd bcdd";
int iBcds = 0;
int iIdx = 0;
while(true) {
int iBcdIdx = sSentence.indexOf("bcd", iIdx);
if(iBcdIdx == -1) {
break;
}
iIdx = iBcdIdx + "bcd".length();
iBcds++;
}
System.out.println("Number of 'bcd's (no regex): " + iBcds);
//Alternatively
iBcds = 0;
//Same regex as #la-comadreja, with word-boundaries
//(for multiple "bcd"-s in a single word, remove the "\\b"-s)
Matcher m = Pattern.compile("\\b\\w*bcd\\w*\\b").matcher(sSentence);
while(m.find()) {
System.out.println("Found at index " + m.start());
iBcds++;
}
System.out.println("Number of 'bcd's (with regex): " + iBcds);
}
}
Output:
[R:\jeffy\programming\sandbox\xbnjava]java BcdRegexXmpl
Number of 'bcd's (no regex): 2
Found at index 0
Found at index 5
Number of 'bcd's (with regex): 2
Your pattern should be:
(a?)(bcd)(d?)
Another possibility is to write it as
\w*bcd\w*
If you want to count the number of "bcd"s in the string:
int bcds = 0;
for (int i = 0; i < str.length() - 2; i++) {
if (str.charAt(i) == 'b' && str.charAt(i+1) == 'c' && str.charAt(i+2) == 'd')
bcds++;
}
A maximally generalizable, concise and readable (and reasonably efficient) non-Regex answer:
int countMatches(String s, String searchStr) {
//Here, s is "abcd bcdd" and searchStr is "bcd"
int matches = 0;
for (int i = 0; i < s.length() - searchStr.length() + 1; i++) {
for (int j = 0; j < searchStr.length(); j++) {
if (s.charAt(i + j) != searchStr.charAt(j)) break;
if (j == searchStr.length() - 1) matches++;
}
}
return matches;
}
I'm writing a program where the user enters a String in the following format:
"What is the square of 10?"
I need to check that there is a number in the String
and then extract just the number.
If i use .contains("\\d+") or .contains("[0-9]+"), the program can't find a number in the String, no matter what the input is, but .matches("\\d+")will only work when there is only numbers.
What can I use as a solution for finding and extracting?
try this
str.matches(".*\\d.*");
If you want to extract the first number out of the input string, you can do-
public static String extractNumber(final String str) {
if(str == null || str.isEmpty()) return "";
StringBuilder sb = new StringBuilder();
boolean found = false;
for(char c : str.toCharArray()){
if(Character.isDigit(c)){
sb.append(c);
found = true;
} else if(found){
// If we already found a digit before and this char is not a digit, stop looping
break;
}
}
return sb.toString();
}
Examples:
For input "123abc", the method above will return 123.
For "abc1000def", 1000.
For "555abc45", 555.
For "abc", will return an empty string.
I think it is faster than regex .
public final boolean containsDigit(String s) {
boolean containsDigit = false;
if (s != null && !s.isEmpty()) {
for (char c : s.toCharArray()) {
if (containsDigit = Character.isDigit(c)) {
break;
}
}
}
return containsDigit;
}
s=s.replaceAll("[*a-zA-Z]", "") replaces all alphabets
s=s.replaceAll("[*0-9]", "") replaces all numerics
if you do above two replaces you will get all special charactered string
If you want to extract only integers from a String s=s.replaceAll("[^0-9]", "")
If you want to extract only Alphabets from a String s=s.replaceAll("[^a-zA-Z]", "")
Happy coding :)
The code below is enough for "Check if a String contains numbers in Java"
Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");
if(m.find()){
System.out.println("Hello "+m.find());
}
I could not find a single pattern correct.
Please follow below guide for a small and sweet solution.
String regex = "(.)*(\\d)(.)*";
Pattern pattern = Pattern.compile(regex);
String msg = "What is the square of 10?";
boolean containsNumber = pattern.matcher(msg).matches();
Pattern p = Pattern.compile("(([A-Z].*[0-9])");
Matcher m = p.matcher("TEST 123");
boolean b = m.find();
System.out.println(b);
The solution I went with looks like this:
Pattern numberPat = Pattern.compile("\\d+");
Matcher matcher1 = numberPat.matcher(line);
Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = stringPat.matcher(line);
if (matcher1.find() && matcher2.find())
{
int number = Integer.parseInt(matcher1.group());
pw.println(number + " squared = " + (number * number));
}
I'm sure it's not a perfect solution, but it suited my needs. Thank you all for the help. :)
Try the following pattern:
.matches("[a-zA-Z ]*\\d+.*")
Below code snippet will tell whether the String contains digit or not
str.matches(".*\\d.*")
or
str.matches(.*[0-9].*)
For example
String str = "abhinav123";
str.matches(".*\\d.*") or str.matches(.*[0-9].*) will return true
str = "abhinav";
str.matches(".*\\d.*") or str.matches(.*[0-9].*) will return false
As I was redirected here searching for a method to find digits in string in Kotlin language, I'll leave my findings here for other folks wanting a solution specific to Kotlin.
Finding out if a string contains digit:
val hasDigits = sampleString.any { it.isDigit() }
Finding out if a string contains only digits:
val hasOnlyDigits = sampleString.all { it.isDigit() }
Extract digits from string:
val onlyNumberString = sampleString.filter { it.isDigit() }
public String hasNums(String str) {
char[] nums = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] toChar = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
toChar[i] = str.charAt(i);
for (int j = 0; j < nums.length; j++) {
if (toChar[i] == nums[j]) { return str; }
}
}
return "None";
}
You can try this
String text = "ddd123.0114cc";
String numOnly = text.replaceAll("\\p{Alpha}","");
try {
double numVal = Double.valueOf(numOnly);
System.out.println(text +" contains numbers");
} catch (NumberFormatException e){
System.out.println(text+" not contains numbers");
}
As you don't only want to look for a number but also extract it, you should write a small function doing that for you. Go letter by letter till you spot a digit. Ah, just found the necessary code for you on stackoverflow: find integer in string. Look at the accepted answer.
.matches(".*\\d+.*") only works for numbers but not other symbols like // or * etc.
ASCII is at the start of UNICODE, so you can do something like this:
(x >= 97 && x <= 122) || (x >= 65 && x <= 90) // 97 == 'a' and 65 = 'A'
I'm sure you can figure out the other values...
I have a string which sometimes gives character value and sometimes gives integer value. I want to get the count of number of digits in that string.
For example, if string contains "2485083572085748" then total number of digits is 16.
Please help me with this.
A cleaner solution using Regular Expressions:
// matches all non-digits, replaces it with "" and returns the length.
s.replaceAll("\\D", "").length()
String s = "2485083572085748";
int count = 0;
for (int i = 0, len = s.length(); i < len; i++) {
if (Character.isDigit(s.charAt(i))) {
count++;
}
}
Just to refresh this thread with stream option of counting digits in a string:
"2485083572085748".chars()
.filter(Character::isDigit)
.count();
If your string gets to big and full of other stuff than digits you should try to do it with regular expressions. Code below would do that to you:
String str = "asdasd 01829898 dasds ds8898";
Pattern p = Pattern.compile("\d"); // "\d" is for digits in regex
Matcher m = p.matcher(str);
int count = 0;
while(m.find()){
count++;
}
check out java regex lessons for more.
cheers!
Loop each character and count it.
String s = "2485083572085748";
int counter = 0;
for(char c : s.toCharArray()) {
if( c >= '0' && c<= '9') {
++counter;
}
}
System.out.println(counter);
public static int getCount(String number) {
int flag = 0;
for (int i = 0; i < number.length(); i++) {
if (Character.isDigit(number.charAt(i))) {
flag++;
}
}
return flag;
}
in JavaScript:
str = "2485083572085748"; //using the string in the question
let nondigits = /\D/g; //regex for all non-digits
let digitCount = str.replaceAll(nondigits, "").length;
//counts the digits after removing all non-digits
console.log(digitCount); //see in console
Thanks --> https://stackoverflow.com/users/1396264/vedant for the Java version above. It helped me too.
int count = 0;
for(char c: str.toCharArray()) {
if(Character.isDigit(c)) {
count++;
}
}
Also see
Javadoc
Something like:
using System.Text.RegularExpressions;
Regex r = new Regex( "[0-9]" );
Console.WriteLine( "Matches " + r.Matches("if string contains 2485083572085748 then" ).Count );