简体   繁体   中英

java regex capturing 2 numbers

I'm looking for a way to capture the year and the last number of a string. ex: "01/02/2017,546.12,24.2," My problem so far I only got Found value : 2017 and Found value : null. I'm not able to capture the group(2). Thanks

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;


public class Bourse {

    public static void main( String args[] ) {
        Scanner clavier = new Scanner(System.in);

        // String to be scanned to find the pattern.
        String line = clavier.nextLine();
        String pattern = "(?<=\\/)(\\d{4})|(\\d+(?:\\.\\d{1,2}))(?=,$)";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);

        if (m.find( )) {
            System.out.println("Found value: " + m.group(1) );
            System.out.println("Found value: " + m.group(2) );
        } else {
            System.out.println("NO MATCH");
        }
    }
}

Try this one:

(\\d{2}\\.?\\d{2})
  • \\\\d{2} - exactly two digits
  • \\\\.? - optional dot
  • \\\\d{2} - exactly two digits

If I understood you correctly you're looking for 4 digits, which could be separated by dot.

Your requirements are not very clear, but this works for me to simply grab the year and the last decimal value:

Pattern pattern = Pattern.compile("[0-9]{2}/[0-9]{2}/([0-9]{4}),[^,]+,([0-9.]+),");
String text = "01/02/2017,546.12,24.2,";
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
    String year = matcher.group(1);
    String lastDecimal = matcher.group(2);
    System.out.println("Year "+year+"; decimal "+lastDecimal);
}

I don't know whether you're deliberately using lookbehind and lookahead, but I think it's simpler to explicitly specify the full date pattern and consume the value between two explicit comma characters. (Obviously if you need the comma to remain in play you can replace the final comma with a lookahead.)

By the way, I'm not a fan of the \\d shorthand because in many languages this will match all digit characters from the entire Unicode character space, when usually only matching of ASCII digits 0-9 is desired. (Java does only match ASCII digits when \\d is used, but I still think it's a bad habit.)

Parse, not regex

Regex is overkill here.

Just split the string on the comma- delimiter .

String input = "01/02/2017,546.12,24.2,";
String[] parts = input.split( "," );

Parse each element into a meaningful object rather than treating everything as text.

For a date-only value, the modern approach uses the java.time.LocalDate class built into Java 8 and later.

// Parse the first element, a date-only value.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate localDate = null;
String inputDate =  parts[ 0 ] ;
try
{
   localDate =  LocalDate.parse( inputDate , f );
} catch ( DateTimeException e )
{
    System.out.println( "ERROR - invalid input for LocalDate: " + parts[ 0 ] );
}

For numbers with decimals where accuracy matters, avoid the floating-point types and instead use BigDecimal . Given your class name “Bourse“, I assume the numbers relate to money, so accuracy matters. Always use BigDecimal for money matters.

// Loop the numbers
List < BigDecimal > numbers = new ArrayList <>( parts.length );
for ( int i = 1 ; i < parts.length ; i++ )
{  // Start index at 1, skipping over the first element (the date) at index 0.
    String s = parts[ i ];
    if ( null == s )
    {
        continue;
    }
    if ( s.isEmpty( ) )
    {
        continue;
    }
    BigDecimal bigDecimal = new BigDecimal( parts[ i ] );
    numbers.add( bigDecimal );
}

Extract your two desired pieces of information: the year, and the last number.

Consider passing around a Year object in your code rather than a mere integer to represent the year. This gives you type-safety and makes your code more self-documenting.

// Goals: (1) Get the year of the date. (2) Get the last number.
Year year = Year.from( localDate );  // Where possible, use an object rather than a mere integer to represent the year.
int y = localDate.getYear( );
BigDecimal lastNumber = numbers.get( numbers.size( ) - 1 );  // Fetch last element from the List.

Dump to console.

System.out.println("input: " + input );
System.out.println("year.toString(): " + year );
System.out.println("lastNumber.toString(): " + lastNumber );

See this code run live at IdeOne.com .

input: 01/02/2017,546.12,24.2,

year.toString(): 2017

lastNumber.toString(): 24.2

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