简体   繁体   中英

How to extract specific String values using regex

I am a newbie in regex, I want to extract values between commas but I don't know how.

I have values like this :

 [1000, Value_to_extract, 1150370.5]

and I used this Technic to simplify it:

String val = "[1000, Value_to_extract, 1150370.5]";

String  designation=val.replace("[",    "").replace("]", "").trim();

It give's me this result :

1000, Value_to_extract, 1150370.5

I don't know how to extract only Value_to_extract

I tried : String designation=val.replace("[", "").replace("]", "").replaceAll(".*, ,.*", "").trim();
but i doesn't work .

Thank you for your help.

String input = "[1000, Value_to_extract, 1150370.5]";
String[] parts = input.replaceAll("\\[\\] ", "")   // strip brackets and whitespace
                      .split(",");                 // split on comma into an array

String valueToExtract = parts[1];                  // grab the second entry

Notes:

You might also be able to use a regex here, qv the answer by @Thomas, but a regex will become unwieldy for extracting values from a CSV string of arbitrary length. So in general, I would prefer splitting here to using a regex.

someting like this:

,[ ]?([0-9]+[.]?[0-9]+),

breakdown

, // literal ,
[ ]? // 0 or 1 spaces
([0-9]+[.]?[0-9]+) // capture a number with or without a dot
, // another litteral ,

https://regex101.com/r/oR7nI8/1

Here are some options:

    String val = "[1000, Value_to_extract, 1150370.5]";

    //you can remove white space by
    String noSpaces = val.trim();
    System.out.println(noSpaces);

    //you can split the string into string[] settting
    //the delimiting regular expression to ", "
    String[] strings = noSpaces.split(", ");
    //the strings[1] will hold the desired string
    System.out.println(strings[1]);

    //in the private case of val, only Value_to_extract contains letters and "_" ,
    //so you can also extract it using
    System.out.println(val.replaceAll("[^a-zA-Z_]", ""));

If val does not well represent the more general need, you need to define the need more precisely.

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