简体   繁体   中英

Using Regular Expressions to Extract a Value in from a string in Java

I have a string as a#1-b#2-c#3-d#4-e#5-f#6-g#7-h#8-i#9-j#0-k#10-l#11 . I want to create a program such that if I give value as a then it should return a#1 , If I give b then it should return b#2 from given string. I am very new to java regular expressions.

Yes, a simple regex should do the trick. Just prepend your input to a regex matching # followed by some numbers (assuming that's the pattern):

String str = "a#1-b#2-c#3-d#4-e#5-f#6-g#7-h#8-i#9-j#0-k#10-l#11";
String input = "a";
Matcher m = Pattern.compile(input + "#\\d+").matcher(str);
if (m.find()) {
    System.out.println(m.group());
}

Probably using RegExpo for such simple task is overhead. Just string search:

public static String get(char ch) {
    final String str = "a#1-b#2-c#3-d#4-e#5-f#6-g#7-h#8-i#9-j#0-k#10-l#11";
    int pos = str.indexOf(ch);

    if (pos < 0)
        return null;

    int end = str.indexOf('-', pos);
    return end < 0 ? str.substring(pos) : str.substring(pos, end);
}

Not better than @shmosel's answer, but if you need to repeatedly extract values, you can build a Map once, then each retrieval will be faster (but initial Map construction will be slow):-

Map<String, String> map = Arrays.stream(str.split("-"))
        .collect(Collectors.toMap(o -> o.substring(0, o.indexOf('#')).trim(), Function.identity()));

Here's the full code:-

String str = "a#1-b#2-c#3-d#4-e#5-f#6-g#7-h#8-i#9-j#0-k#10-l#11";
Map<String, String> map = Arrays.stream(str.split("-"))
        .collect(Collectors.toMap(o -> o.substring(0, o.indexOf('#')).trim(), Function.identity()));
System.out.println(map.get("a"));

Output: a#1

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