Java 提取特定单词后由分隔符分隔的值

Java 提取特定单词后由分隔符分隔的值,java,regex,match,Java,Regex,Match,假设a有一个类似以下内容的主字符串: “最近的价格是三星(100.59)、诺基亚(35.23)、苹果(199.34)”。 是否有任何方法通过发送名称从该字符串中提取值 公共双getValue(字符串名称) 因此,getValue(“诺基亚”)将返回35.23,getValue(苹果)将返回199.34。以下是一些适用于您的示例的内容 public static void main(String[] args) { String s = "The last prices are Samsu

假设a有一个类似以下内容的主字符串: “最近的价格是三星(100.59)、诺基亚(35.23)、苹果(199.34)”。 是否有任何方法通过发送名称从该字符串中提取值

公共双getValue(字符串名称)


因此,getValue(“诺基亚”)将返回35.23,getValue(苹果)将返回199.34。

以下是一些适用于您的示例的内容

public static void main(String[] args) {
    String s = "The last prices are Samsung(100.59), Nokia(35.23), Apple(199.34)";
    System.out.println(getValue(s, "Samsung"));
    System.out.println(getValue(s, "Nokia"));
    System.out.println(getValue(s, "Apple"));
}

private static String getValue(String text, String valueOf) {
    int fromIndex = text.indexOf(valueOf);
    int start = text.indexOf("(", fromIndex);
    int end = text.indexOf(")", fromIndex);
    return text.substring(start + 1, end);
}

在你的情况下,这里有一些有用的东西

public static void main(String[] args) {
    String s = "The last prices are Samsung(100.59), Nokia(35.23), Apple(199.34)";
    System.out.println(getValue(s, "Samsung"));
    System.out.println(getValue(s, "Nokia"));
    System.out.println(getValue(s, "Apple"));
}

private static String getValue(String text, String valueOf) {
    int fromIndex = text.indexOf(valueOf);
    int start = text.indexOf("(", fromIndex);
    int end = text.indexOf(")", fromIndex);
    return text.substring(start + 1, end);
}

你可以用正则表达式来做这个

public Double getValue(String name){
    Pattern p = Pattern.compile("(?<=" + name + "\\()\\d+\\.\\d+(?=\\))");
    Matcher m = p.matcher("<your matcher string>");
    m.find();
    return Double.parseDouble(m.group());
}
public双精度getValue(字符串名称){

Pattern p=Pattern.compile((?您可以使用regex来完成此操作

public Double getValue(String name){
    Pattern p = Pattern.compile("(?<=" + name + "\\()\\d+\\.\\d+(?=\\))");
    Matcher m = p.matcher("<your matcher string>");
    m.find();
    return Double.parseDouble(m.group());
}
public双精度getValue(字符串名称){

Pattern p=Pattern.compile((?在API中,不是。您已经编写了自己的逻辑。基于
String.indexOf(“诺基亚”)
\w\(\d+)(\d+))编写自己的逻辑有什么错
您可以尝试使用此正则表达式获取名称和值,然后将其拆分到括号中。在API中,否。您已经编写了自己的逻辑。基于
String.indexOf(“诺基亚”)
\w\(\d+(\.\d+))编写自己的逻辑有什么错
您可以尝试使用这个正则表达式来获取带有值的名称,然后将其拆分到括号中只是一个改进,最好放在
Pattern.compile((?只是一个改进,最好放在
Pattern.compile(?