3
$\begingroup$

I want to copy a section of a string, which lies between two fixed string sections. How to do it?

For example if the string is "...\abcd124\145@cvdf\efgh...". How to tell Mathematica to copy the number between abcd124\ and @cvdf, which is 145.

Here "..." means that the string continues on both sides, but may be different for each case.

thanks

$\endgroup$
3
$\begingroup$
  1. Split the string on the backslash \\
  2. Find the part that ends with @cvdf
  3. Take the digits and convert to an expression, then use FromDigits to get the final number.
str = "...\\abcd124\\145@cvdf\\efgh...";

FromDigits@
 ToExpression[
  StringCases[
   SelectFirst[StringSplit[str, "\\"], StringEndsQ[#, "@cvdf"] &], 
   DigitCharacter]]
$\endgroup$
2
  • $\begingroup$ Thanks.. but how to convert single slash to double slash.. $\endgroup$
    – user49535
    Aug 2 at 10:30
  • $\begingroup$ It worked! Thanks $\endgroup$
    – user49535
    Aug 2 at 10:58
4
$\begingroup$

To find a numeric value between the strings "abcd124\" and "@cvdf", we can use a named pattern and StringCases. Assume the pattern happens only once within string.

string = "\\abcd124\\145@cvdf\\efgh";
ToExpression[First@StringCases[string, "abcd124\\"~~x:DigitCharacter..~~"@cvdf"->x]]

Get the same result using RegularExpression with this expression:

ToExpression[First@StringCases[string, RegularExpression["abcd124\\\\(\\d+)@cvdf"]->"$1"]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.