I am trying to get the value between quotes for a particular string
For example, for the 'IsEmployee' key, I need to get the value 'Yes'
id:'1234',Salary:'200000',Year:'2018',IsEmployee:'Yes'
can anyone please share any sample regex for this
It seems JSON format, although as a string. Please use JSON parser for more flexibility to get any value by keys, or print all
Try this
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexpApp {
public static void main(String[] args){
String val = "id:'1234',Salary:'200000',Year:'2018',IsEmployee:'Yes'";
System.out.println(getValue(val, "id"));
System.out.println(getValue(val, "Year"));
System.out.println(getValue(val, "IsEmployee"));
}
public static String getValue(String testStr, String key){
Pattern p = Pattern.compile("\\b"+key+"[ ]*:[ ]*'(.+?)'");
Matcher m = p.matcher(testStr);
return m.find() ? m.group(1): null;
}
}
You can use the following regex:
(?i)(?<=isemployee:')[^']*
Explanation:
(?i)
- makes the regex case-insensitive (?<=isemployee:')
- positive lookbehind to find the position which is just preceded by isemployee:'
[^']*
- matches 0+ occurrences of any character that is not a '
. In short, it matches everything until the next '
is found in the stringCode: OUTPUT
import java.util.*;
import java.lang.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Rextester
{
public static void main(String args[])
{
final String regex = "(?i)(?<=isemployee:')[^']*";
final String string = "id:'1234',Salary:'200000',Year:'2018',IsEmployee:'Yes'";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
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.