How to extract a substring using regex

前端 未结 14 1286
暖寄归人
暖寄归人 2020-11-22 13:37

I have a string that has two single quotes in it, the \' character. In between the single quotes is the data I want.

How can I write a regex to extract

相关标签:
14条回答
  • 2020-11-22 14:36
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Test {
        public static void main(String[] args) {
            Pattern pattern = Pattern.compile(".*'([^']*)'.*");
            String mydata = "some string with 'the data i want' inside";
    
            Matcher matcher = pattern.matcher(mydata);
            if(matcher.matches()) {
                System.out.println(matcher.group(1));
            }
    
        }
    }
    
    0 讨论(0)
  • 2020-11-22 14:37

    Some how the group(1) didnt work for me. I used group(0) to find the url version.

    Pattern urlVersionPattern = Pattern.compile("\\/v[0-9][a-z]{0,1}\\/");
    Matcher m = urlVersionPattern.matcher(url);
    if (m.find()) { 
        return StringUtils.substringBetween(m.group(0), "/", "/");
    }
    return "v0";
    
    0 讨论(0)
提交回复
热议问题