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];
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));
}
}
}
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));
}
10 回答
你不需要正则表达式 .
将apache commons lang添加到您的项目(http://commons.apache.org/proper/commons-lang/),然后使用:
我同意Mihai Toader的上述答案,就像一个魅力 . 根据更新对它进行一些小修改 .
运行示例:JSFiddle
在javascript中:
实际的正则表达式是:
/'([^']+)'/
如果您使用非贪婪修饰符(根据另一篇文章),它是这样的:
它更清洁 .
在斯卡拉,
因为你还勾选了Scala,这是一个没有正则表达式的解决方案,可以轻松处理多个带引号的字符串:
String dataIWant = mydata.split("'")[1];
见Live Demo
这有一个简单的单行:
通过使匹配组可选,这也适用于在这种情况下通过返回空白而找不到引号 .
见live demo .
假设您想要单引号之间的部分,请将此正则表达式与Matcher一起使用:
例:
结果: