Comment extraire une sous-chaîne en utilisant regex

J’ai une chaîne qui contient deux guillemets simples, le caractère ' . Entre les guillemets simples se trouvent les données que je veux.

Comment puis-je écrire une regex pour extraire “les données que je veux” du texte suivant?

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

En supposant que vous voulez la partie entre guillemets simples, utilisez cette expression régulière avec un Matcher :

 "'(.*?)'" 

Exemple:

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

Résultat:

 les données que je veux

Vous n’avez pas besoin de regex pour cela.

Ajoutez apache commons lang à votre projet ( http://commons.apache.org/proper/commons-lang/ ), puis utilisez:

 Ssortingng dataYouWant = SsortingngUtils.subssortingngBetween(mydata, "'"); 
 import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(Ssortingng[] args) { Pattern pattern = Pattern.comstack(".*'([^']*)'.*"); Ssortingng mydata = "some ssortingng with 'the data i want' inside"; Matcher matcher = pattern.matcher(mydata); if(matcher.matches()) { System.out.println(matcher.group(1)); } } } 

Parce que vous avez également coché Scala, une solution sans regex qui gère facilement plusieurs chaînes entre guillemets:

 val text = "some ssortingng with 'the data i want' inside 'and even more data'" text.split("'").zipWithIndex.filter(_._2 % 2 != 0).map(_._1) res: Array[java.lang.Ssortingng] = Array(the data i want, and even more data) 

Il y a un simple traceur pour cela:

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

En rendant le groupe de correspondance facultatif, cela permet également de ne pas trouver de guillemets en renvoyant un blanc dans ce cas.

Voir la démo en direct .

 Ssortingng dataIWant = mydata.replaceFirst(".*'(.*?)'.*", "$1"); 

comme en javascript:

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

l’expression rationnelle est: /'([^']+)'/

Si vous utilisez le modificateur non gourmand (comme dans un autre article), c’est comme ceci:

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

c’est plus propre

À Scala,

 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 

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

Voir la démo en direct