我试图获取特定字符串的引号之间的值 例如,对于'IsEmployee'关键,我需要得到价值'是'
ID:' 1234',薪酬:' 200000',年份:' 2018',IsEmployee:'是'
任何人都可以分享任何样本正则表达式
答案 0 :(得分:1)
它似乎是JSON格式,虽然是一个字符串。请使用JSON解析器以更灵活地通过键获取任何值,或者打印所有
答案 1 :(得分:1)
试试这个
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;
}
}
答案 2 :(得分:1)
您可以使用以下正则表达式:
(?i)(?<=isemployee:')[^']*
<强>解释强>
(?i)
- 使正则表达式不区分大小写(?<=isemployee:')
- 找到位置的正面观察,其前面是isemployee:'
[^']*
- 匹配任何不是'
的字符的0次出现。简而言之,它匹配所有内容,直到在字符串'
代码: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));
}
}
}
}