[英]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
我不知道如何只提取
Value_to_extract
I tried : String designation=val.replace("[", "").replace("]", "").replaceAll(".*, ,.*", "").trim();
我试过:
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. 你可能也可以在这里使用正则表达式,qv @Thomas的答案,但正则表达式将变得难以从任意长度的CSV字符串中提取值。 So in general, I would prefer splitting here to using a regex.
所以一般来说,我更喜欢在这里拆分使用正则表达式。
someting like this: 像这样:
,[ ]?([0-9]+[.]?[0-9]+),
, // 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 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. 如果val不能很好地代表更普遍的需求,则需要更精确地定义需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.