Java regex is digit

Extract Numbers From String Using Java Regular Expressions

The following are examples which show how to extract numbers from a string using regular expressions in Java.

Being able to parse strings and extract information from it is a key skill that every tester should have. This is particularly useful when testing APIs and you need to parse a JSON or XML response.

The following Java Regular Expression examples focus on extracting numbers or digits from a String.

Extract All Numbers from a String

import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples < public static void main(String[]args) < Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher("string1234more567string890"); while(m.find()) < System.out.println(m.group()); >> > 

Extract nth Digit from a String

If you want to extract only certain numbers from a string you can provide an index to the group() function.

Читайте также:  Javascript date to iso date string

For example, if we wanted to only extract the second set of digits from the string string1234more567string890 , i.e. 567 then we can use:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples < private static final Pattern p = Pattern.compile("[^\\d]*[\\d]+[^\\d]+([\\d]+)"); public static void main(String[] args) < // create matcher for pattern p and given string Matcher m = p.matcher("string1234more567string890"); // if an occurrence if a pattern was found in a given string. if (m.find()) < System.out.println(m.group(1)); // second matched digits >> > 

Explanation of the Pattern [^\d]*[\d]+[^\d]+([\d]+)

  • ignore any non-digit
  • ignore any digit (first number)
  • again ignore any non-digit
  • capture the second number

Extract Number from a Tag Attribute

When dealing with XML or HTML tags, sometimes there is a need to extract a value from an attribute. For example, consider the following tag

To extract number 9999 we can use the following code:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples < public static void main(String[]args) < Pattern pattern = Pattern.compile("numFound=\"(9+)\""); Matcher matcher = pattern.matcher(""); if (matcher.find()) < System.out.println(matcher.group(1)); >> > 

Extract a String Containing digits and Characters

You can use Java regular expressions to extract a part of a String which contains digits and characters. Suppose we have this string Sample_data = YOUR SET ADDRESS IS 6B1BC0 TEXT and we want to extract 6B1BC0 which is 6 characters long, we can use:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples < public static void main (String[] args) < Pattern p = Pattern.compile("YOUR SET ADDRESS IS\\s+([A-Z0-9])"); Matcher n = p.matcher("YOUR SET ADDRESS IS 6B1BC0 TEXT"); if (n.find()) < System.out.println(n.group(1)); // Prints 123456 >> > 

Extract Key-Value Pairs With Regular Expressions

Let’s suppose we have a string of this format bookname=testing&bookid=123456&bookprice=123.45 and we want to extract the key-value pair bookid=123456 we would use:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples < public static void main(String[] args) < String s = "bookname=cooking&bookid=123456&bookprice=123.45"; Pattern p = Pattern.compile("(?<=bookid=)\\d+"); Matcher m = p.matcher(s); if (m.find()) < System.out.println(m.group()); >> > 

Источник

Check if String contains number in Java

To check if string contains number in Java, you can either loop over each character of string and check if it’s a digit or you can use regex.

public static boolean checkIfStringContainsDigit(String passCode) < for (int i = 0; i < passCode.length(); i++) < if(Character.isDigit(passCode.charAt(i))) < return true; >> return false; >

Introduction

There are situations when we need to find if our string contains numbers, lowercase letter, uppercase letter, special character etc. One such example is password. In order to define its strength, we create a protocol on the length of password as well as the characters it contains. To determine that we need to check the string if it contains required characters.

In this article we are going to learn about the regex methods provided by Java. We will also define a method based on loop to check character by character.

Code Example 1: Check digit in string

In this code, we will write a java method which can detect if the string contains a digit.

public static boolean checkIfStringContainsDigit(String passCode) < for (int i = 0; i < passCode.length(); i++) < if(Character.isDigit(passCode.charAt(i))) < return true; >> return false; >

Here we have created a method checkIfStringContainsDigit which accepts a string parameter passCode . It then loops over the length of the string and check each character if that is a digit using isDigit method from Character class. Our method returns true as soon as it finds the first digit or return false after the loop ends.

Code Example 2: Using regex

Now we will check how java regex could be used to look into the string for different kinds of characters.

public int multiChecker(String pass) < int passwordStrength = 0; int conditionsFulfilled = 0; if (Pattern.compile("8").matcher(pass).find()) < passwordStrength = passwordStrength + 10; conditionsFulfilled += 1; >if (Pattern.compile("[a-z]").matcher(pass).find()) < passwordStrength = passwordStrength + 5; conditionsFulfilled += 1; >if (Pattern.compile("[A-Z]").matcher(pass).find()) < passwordStrength = passwordStrength + 15; conditionsFulfilled += 1; >return passwordStrength + (conditionsFulfilled * 5); >

In the above code we have created a method multiChecker which accepts a string parameter pass . The purpose of this code is to check if pass contains digits, lowercase and uppercase letters. Accordingly we are determining the strength of password as well as the number of conditions fulfilled.

For this we are using Pattern and matcher functionality. It compiles the provided regex and then match it with the string.

Источник

Numbers only regex (digits only) Java

Numbers only (or digits only) regular expressions can be used to validate if a string contains only numbers.

Basic numbers only regex

Below is a simple regular expression that allows validating if a given string contains only numbers:

Enter a text in the input above to see the result

Real number regex

Real number regex can be used to validate or exact real numbers from a string.

Enter a text in the input above to see the result

 > 

Enter a text in the input above to see the result

Notes on number only regex validation

In Java you can also validate number by trying to parse it:

 catch (NumberFormatException nfe)

Create an internal tool with UI Bakery

Discover UI Bakery – an intuitive visual internal tools builder.

Источник

How to check if a String is Number in Java — Regular Expression Example

In order to build a regular expression to check if String is a number or not o r if String contains any non-digit character or not you need to learn about character set in Java regular expression, Which we are going to see in this Java regular expression example. No doubt Regular Expression is a great tool in a developer’s arsenal and familiarity or some expertise with regular expression can help you a lot. Java supports regular expression using j ava.util.regex.Pattern and java.util.regex.Matchter class, you can see a dedic ated package java.util.regex for a regular expression in Java. Java supports regex from JDK 1.4, which means well before Generics, Enum, or Autoboxing.

If you are writing server-side code in Java programming language then you may be familiar with the importance of regular expression which is key in parsing certain kinds of messages e. g. FIX Messages used in Electronic trading.

In order to par se Repeating groups in FIX protocol y ou really need an understanding of regular expression in Java. Any way In order to learn validating numbers using regular expression we will start with a simple example

1) Check if a String is a number or not using regular expression

to clarify the requirement, a String would be a number if it contains digits. we have omitt ed decimal point a nd sign or + or — for simplicity.

If you are familiar with a predefined character class in Java regular an expression that you must know that \d will represent a digit (0-9) and \D will represent a non-digit (anything other than 0 to 9). Now using this predefined character class, a String will not be a number if it contains any non digit characters, which can be written in Java regular expression as:

which checks for non digit character anywhere in th e String. T his pattern return true if String contains any thing other than 0-9 digit, which can be used to know if an String is number or not using regular expression.

Same regular expression for checking String for numbers can also be written without using predefined character set and using character class and negation as shown in following example :

This is similar to the above regex pattern, the only difference is \D is replaced by [^0-9]. By the way, there are always multiple ways to check for certain things using regex.

2. Verify if a String is a six-digit number or not using regular expression

This is a kind of special regular expression requirement for validating data like id , zipcode or any other pure numerical data. In order to check for digits you can either use character class 6 or use short-form \d . here is a simple regular expression in Java which can check if a String contains 6 digits or not:

Pattern digitPattern = Pattern. compile ( » \\ d \\ d \\ d \\ d \\ d \\ d» ) ;

above pattern checks each character for digit six times. This pattern can also be written in much shorter and readable format as :

where <6>denote six times. you can also replace \d with character class 5 and it should work. You can further see these Java Regular expression courses to learn more about different regular expression patterns.

Code Example — Regular expression in Java to check numbers

Here is a complete code example in Java programming language to check if a String is an integer number or not. In this Java program, we are using regular expressions to check if String contains only digits i.e. 0 to 9 or not. If String only contains a digit then its number otherwise it’s not a numeric String.

One interesting point to note is that this regular expression only checks for integer numbers as it not looking for dot(.) characters, which means floating point or decimal numbers will fail this test.

import java.util.regex.Pattern ;
/**
* Java program to demonstrate use of Regular Expression to check

* if a String is a 6 digit number or not.
*/
public class RegularExpressionExample

public static void main ( String args [])

// Regular expression in Java to check if String is a number or not
Pattern pattern = Pattern. compile ( «.*[^0-9].*» ) ;
//Pattern pattern = Pattern.compile(«.*\\D.*»);
String [] inputs = < "123" , "-123" , "123.12" , "abcd123" >;

for ( String input: inputs ) <
System. out . println ( «does » + input + » is number : «

+ ! pattern. matcher ( input ) . matches ()) ;
>

// Regular expression in java to check if String is 6 digit number or not
String [] numbers = < "123" , "1234" , "123.12" , "abcd123" , "123456" >;
Pattern digitPattern = Pattern. compile ( » \\ d» ) ;

+ digitPattern. matcher ( number ) . matches ()) ;
>
>

Output:
does 123 is number : true
does — 123 is number : false
does 123.12 is number : false
does abcd123 is number : false

does 123 is 6 digit number : false
does 1234 is 6 digit number : false
does 123.12 is 6 digit number : false
does abcd123 is 6 digit number : false
does 123456 is 6 digit number : true

That’s all on using Java regular expression to check numbers in String. As you have seen in this Java Regular Expression example that it’s pretty easy and fun to do the validation using regular expression.

Источник

Java Regular Expression to Check If String contains at least One Digit

This week’s task is to write a regular expression in Java to check if a String contains any digit or not. For example, passing «abcd» to pattern should false , while passing «abcd1» to return true , because it contains at least one digit. Similarly passing «1234» should return true because it contains more than one digit. Though java.lang.String class provides a couple of methods with inbuilt support of regular expression like split method, replaceAll(), and matches method, which can be used for this purpose, but they have a drawback. They create a new regular expression pattern object, every time you call. Since most of the time we can just reuse the pattern, we don’t need to spend time on creating and compiling patterns, which is expensive compared to testing a String against the pattern.

For reusable patterns, you can take the help of java.util.regex package, it provides two class Pattern and Matcher to create pattern and check String against that pattern.

In order to complete this, we first need to create a regular expression pattern object, we can do that by passing regular expression String «(.)*(\\d)(.)*» to Pattern.compile() method, this returns a compiled version of regular expression String. By using this pattern you can get Matcher object to see if the input string passes this regular expression pattern or not.

We will learn more about our regular expression String in the next section when we will see our code example to check if String contains a number or not.

Regular Expression to Find if String contains Number or Not

The following code sample is our complete Java program to check if String contains any number or not. You can copy this code into your favorite IDE like Eclipse, Netbeans, or IntelliJ IDEA. Just create a Java source file with the name of our public class RegularExpressionDemo and run it from IDE itself.

Alternatively, you can run the Java program from the command line by first compiling a Java source file using the javac compiler and then running it using the java command.

Now let’s understand the core of the program, the regular expression itself. We are using «(.)*(\\d)(.)*» , where dot and start are meta characters used for any character and any number of timer. \d is a character class for matching digits, and since backward slash needs to escaped in Java, we have put another backslash e.g. \\d ..

So if you read this regular expression, it days any character any number of time, followed by any digit then again any character any number of time. This means this will match any String which contains any numeric digit e.g. from 0 — 9.

Regular Expression in Java for Checking if String contains Number

import java.util.Scanner ;

Источник

Оцените статью