0

For example lets take a string {"hello":"world"}

and another string {"hi":"hello"}

I want to search for the hello in the first string that is before the colon(:)

but my code is finding and returning the string which has the specified queried string but not the string which has the queried string only before colon, i.e., the left hand side part

here the list contains list of strings

for(int i = 0; i < list.size; i++)
{
if(list.get(i).contains(query))
list.remove(i);
}

that means it is finding the first appearing string which has the specified query but not the string until the specified character

Novice
  • 84
  • 1
  • 8
  • 1
    Why do you not parse the JSON string with a JSON library? – Progman Dec 31 '20 at 21:02
  • If you're trying to read JSON, have you tried using a library such as JsonPath? It might make things easier https://github.com/json-path/JsonPath – Heuriskos Dec 31 '20 at 21:04
  • Because these strings are stored in a text file which will be in the form of strings – Novice Dec 31 '20 at 21:04
  • 1
    JSON is a text format, so it's usually retrieved as a String, which you can parse as JSON to obtain objects (or arrays or primitives) instead. If you want an analogy, imagine you're reading a file that contains a number. You're first going to read a String sure, but it would be much more helpful to cast it to a relevant subclass of Number – Aaron Dec 31 '20 at 21:05
  • 1
    Does this answer your question? [How to parse JSON in Java](https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – Progman Dec 31 '20 at 21:06

1 Answers1

2

If the string is part of a JSON file, you should use a JSON parser. If not, you can use the Java regex API as follows:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String input = "{\"hello\":\"world\"}";
        Matcher matcher = Pattern.compile("\\w+(?=.*:)").matcher(input);
        if (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

Output:

hello

Explanation of the regex:

  1. \w+ specifies one or more word characters.
  2. (?=.*:) specifies positive lookahead for .*: where .* specifies any number of any character(s). The . specify any character and * is used as a quantifier, zero or more times.
  3. : specifies the character literal, :
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • I got the point but imagine there are list of strings and if I want to search for a substring in the list elements and perform the above operation how can I do it? – Novice Dec 31 '20 at 21:49
  • @Novice - In that case, you just need to put the whole thing inside the loop iterating the list i.e. `for (String input : list) { Matcher matcher = Pattern.compile("\\w+(?=.*:)").matcher(input); if (matcher.find()) { System.out.println(matcher.group()); } }` – Arvind Kumar Avinash Dec 31 '20 at 23:17