简体   繁体   中英

Java regex pattern for number

I know that this question can be stupid but I am trying to get some information from text and you are my last hope after last three hours of trying..

DIC: C/40764176 IC: 407641'6 
Dekujerne a t8ime se na shledanou 

I need to get for example this 40764176

I need to get string with 8-10 length, sometimes there can be some special chars like I,i,G,S,O,ó,l) but I have tried a lot of patterns for this and no one works...

I tried:

String generalDicFormatPattern = "([0-9IiGSOól]{8,10})";
String generalDicFormatPattern = ".*([0-9IiGSOól]{8,10}).*";
String generalDicFormatPattern = "\\b([0-9IiGSOól]{8,10})\\b";

nothing works... do you know where is the problem?

edit:

I use regex in this way:

private List<String> getGeneralDicFromLine(String concreteLine) {
    List<String> allMatches = new ArrayList<String>();

        Pattern pattern = Pattern.compile(generalDicFormatPattern);
        Matcher matcher = pattern.matcher(concreteLine);

        while (matcher.find()) {             
             allMatches.add(matcher.group(1));
        }                           


    return allMatches;
}   

If your string's pattern is fixed you can use the regex

C/([^\s]{8,10})\sIC:

Sample code:

String s = "DIC: C/40764176 IC: 407641'6";

Pattern p = Pattern.compile("C/([^\\s]{8,10})\\sIC:");
Matcher m = p.matcher(s);

if (m.find()) {
    System.out.println(m.group(1)); // 40764176
}

I'm expecting any character (includes the special ones you've shown in examples) but a white space.

May be you can split your string with spaces ( string.split('\\\\s'); ), then you should have an array like this :

  1. DIC:
  2. C/40764176
  3. IC: 407641'6
  4. ...
  5. shledanou

Get the second string, split it using '/', and get the second element.

I hope it helped you.

Tip : you can check after the result using a regex ( ([0-9IiGSOól]{8,10} )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM