Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating regex to extract 4 digit number from string using java

Hi I am trying to build one regex to extract 4 digit number from given string using java. I tried it in following ways:

String mydata = "get the 0025 data from string";
    Pattern pattern = Pattern.compile("^[0-9]+$");
    //Pattern pattern = Pattern.compile("^[0-90-90-90-9]+$");
    //Pattern pattern = Pattern.compile("^[\\d]+$");
    //Pattern pattern = Pattern.compile("^[\\d\\d\\d\\d]+$");

    Matcher matcher = pattern.matcher(mydata);
    String val = "";
    if (matcher.find()) {
        System.out.println(matcher.group(1));

        val = matcher.group(1);
    }

But it's not working properly. How to do this. Need some help. Thank you.

like image 510
nilkash Avatar asked Jun 02 '15 08:06

nilkash


People also ask

How does regex match 4 digits?

Add the $ anchor. /^SW\d{4}$/ . It's because of the \w+ where \w+ match one or more alphanumeric characters. \w+ matches digits as well.

How do you input a 4 digit number in Java?

String pin = obj. nextLine(); To check if this pin contains 4 digits, we can use the regex \d{4} .

How do you find digits in regex?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ).

How to extract numbers from a string using regex in Java?

How to extract numbers from a string using regex in Java? Extracting all numeric data from the string content is a very common and useful scenerio and can be achieved using a regex pattern. The basic pattern we need to use is a “ [0-9]”, i.e. character class of digits from 0 to 9.

What is Java regex?

Java Regex. The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings. It is widely used to define the constraint on strings such as password and email validation. After learning Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.

How to test regular expression in Java?

It is widely used to define the constraint on strings such as password and email validation. After learning Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.

How do I make a string only have 4 digits?

You can go with \d {4} or [0-9] {4} but note that by specifying the ^ at the beginning of regex and $ at the end you're limiting yourself to strings that contain only 4 digits. My recomendation: Learn some regex basics. Show activity on this post.


1 Answers

Change you pattern to:

Pattern pattern = Pattern.compile("(\\d{4})");

\d is for a digit and the number in {} is the number of digits you want to have.

like image 135
Jens Avatar answered Oct 09 '22 00:10

Jens