![](/img/trans.png)
[英]Extract specific values or substrings from long string using regex in java
[英]How to extract specific String values using regex
我是正則表達式的新手,我想在逗號之間提取值,但我不知道如何。
我有這樣的價值觀:
[1000, Value_to_extract, 1150370.5]
我使用這個技術來簡化它:
String val = "[1000, Value_to_extract, 1150370.5]";
String designation=val.replace("[", "").replace("]", "").trim();
它給了我這個結果:
1000, Value_to_extract, 1150370.5
我不知道如何只提取Value_to_extract
我試過: String designation=val.replace("[", "").replace("]", "").replaceAll(".*, ,.*", "").trim();
但我不行。
謝謝您的幫助。
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
筆記:
你可能也可以在這里使用正則表達式,qv @Thomas的答案,但正則表達式將變得難以從任意長度的CSV字符串中提取值。 所以一般來說,我更喜歡在這里拆分使用正則表達式。
像這樣:
,[ ]?([0-9]+[.]?[0-9]+),
, // literal ,
[ ]? // 0 or 1 spaces
([0-9]+[.]?[0-9]+) // capture a number with or without a dot
, // another litteral ,
以下是一些選項:
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_]", ""));
如果val不能很好地代表更普遍的需求,則需要更精確地定義需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.