首页 文章

如何使用正则表达式提取子字符串

提问于
浏览
301

我有一个字符串,其中有两个单引号,即 ' 字符 . 在单引号之间是我想要的数据 .

如何编写正则表达式以从以下文本中提取“我想要的数据”?

mydata = "some string with 'the data i want' inside";

10 回答

  • 3

    你不需要正则表达式 .

    将apache commons lang添加到您的项目(http://commons.apache.org/proper/commons-lang/),然后使用:

    String dataYouWant = StringUtils.substringBetween(mydata, "'");
    
  • 58

    我同意Mihai Toader的上述答案,就像一个魅力 . 根据更新对它进行一些小修改 .

    let string = "fact-tab-1 extra stuff you dont care about"
    
    let matchResult = string.match(/fact-tab-./);
    
    console.log(matchResult)
    
    console.log('The extracted part would be : ' + matchResult[0])
    document.getElementById('result').innerHTML = 'The extracted part would be : ' + matchResult[0];
    
    <div id="result">
    </div>
    

    运行示例:JSFiddle

  • 461
    String dataIWant = mydata.replaceFirst(".*'(.*?)'.*", "$1");
    
  • 9

    在javascript中:

    mydata.match(/'([^']+)'/)[1]
    

    实际的正则表达式是: /'([^']+)'/

    如果您使用非贪婪修饰符(根据另一篇文章),它是这样的:

    mydata.match(/'(.*?)'/)[1]
    

    它更清洁 .

  • 0

    在斯卡拉,

    val ticks = "'([^']*)'".r
    
    ticks findFirstIn mydata match {
        case Some(ticks(inside)) => println(inside)
        case _ => println("nothing")
    }
    
    for (ticks(inside) <- ticks findAllIn mydata) println(inside) // multiple matches
    
    val Some(ticks(inside)) = ticks findFirstIn mydata // may throw exception
    
    val ticks = ".*'([^']*)'.*".r    
    val ticks(inside) = mydata // safe, shorter, only gets the first set of ticks
    
  • 6

    因为你还勾选了Scala,这是一个没有正则表达式的解决方案,可以轻松处理多个带引号的字符串:

    val text = "some string with 'the data i want' inside 'and even more data'"
    text.split("'").zipWithIndex.filter(_._2 % 2 != 0).map(_._1)
    
    res: Array[java.lang.String] = Array(the data i want, and even more data)
    
  • 9
    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));
            }
    
        }
    }
    
  • 2

    String dataIWant = mydata.split("'")[1];

    Live Demo

  • 5

    这有一个简单的单行:

    String target = myData.replaceAll("[^']*(?:'(.*?)')?.*", "$1");
    

    通过使匹配组可选,这也适用于在这种情况下通过返回空白而找不到引号 .

    live demo .

  • 2

    假设您想要单引号之间的部分,请将此正则表达式与Matcher一起使用:

    "'(.*?)'"
    

    例:

    String mydata = "some string with 'the data i want' inside";
    Pattern pattern = Pattern.compile("'(.*?)'");
    Matcher matcher = pattern.matcher(mydata);
    if (matcher.find())
    {
        System.out.println(matcher.group(1));
    }
    

    结果:

    the data i want
    

相关问题