How to extract specific variables from a string?

Asked
Active3 hr before
Viewed126 times

7 Answers

extractstringvariablesspecific
90%

Am I able to mark mines with the bottom row of 3's? ,You'll find it difficult name variables based on values from a string (A1, A2, etc). It's better to use a dictionary to store this type of data., An engineering enigma: the useless "wings" behind giant robots. What is their TRUE purpose? , Overfitting, but why is the training deviance dropping?

Original String

x = "A:22.0 /4.03 B:15.05 /3.0, C:120.15 /12.4"

Replace special characters w/space and split on spaces (will remove extra whitespace)

b = x.replace(':', ' ').replace('/', ' ').split()

Gives you

['A', '22.0', '4.03', 'B', '15.05', '3.0,', 'C', '120.15', '12.4']

Construct a dictionary from your data

output = {
   b[x]: [b[x + 1], b[x + 2]]
   for x in range(0, len(b), 3)
}

Output:

{
   'A': ['22.0', '4.03'],
   'B': ['15.05', '3.0,'],
   'C': ['120.15', '12.4']
}

Then access the data as such:

output['A'][0]
22.0
output['A'][1]
4.03
load more v
88%

For regexs, that is, to recall all or a portion of a string, the syntax is:,These expressions can be combined to search for a wide variety of strings.,([a-zA-Z]+) – subexpression capturing a string consisting of letters. This will be the last name., There are three parts in this regular expression:

input str60 address
   "4905 Lakeway Drive, College Station, Texas 77845 USA"
"673 Jasmine Street, Los Angeles, CA 90024"
"2376 First street, San Diego, CA 90126"
"6 West Central St, Tempe AZ 80068"
"1234 Main St. Cambridge, MA 01238-1234"
end
load more v
72%

Are there countries that ban public sector unions, but allow private sector ones? , Using \bigtriangledown as the nabla operator: accents ,Asking for help, clarification, or responding to other answers., Dent below seat stay on a steel frame safe to ride?

It is best to do this with an associative array. e.g.

declare - A array

while IFS =: read key val;
do
   array["$key"] = "$val"
done < input.txt

for key in Total_Test_Cases_Count Total_Pass;
do
   printf '%s=%s\n'
"$key"
"${array[$key]}"
done

Output:

Total_Test_Cases_Count = 25
Total_Pass = 24

This will fail if any of the values contain the field separator (a colon, :). In that case, you first need to change the field separator in the input to something that isn't in either of the fields. A tab is often a good choice. For example:

while IFS = $ '\t'
read key val;
do
   array["$key"] = "$val"
done < < (sed - e 's/:/\t/1'
   input.txt)
load more v
65%

The main reason for extracting variables is to make a complex expression more understandable, by dividing it into its intermediate parts. These could be:,More readable code! Try to give the extracted variables good names that announce the variable’s purpose loud and clear. More readability, fewer long-winded comments. Go for names like customerTaxValue, cityUnemploymentRate, clientSalutationString, etc.,Place the result of the expression or its parts in separate variables that are self-explanatory.,Insert a new line before the relevant expression and declare a new variable there. Assign part of the complex expression to this variable.

void renderBanner() {
   if ((platform.toUpperCase().indexOf("MAC") > -1) &&
      (browser.toUpperCase().indexOf("IE") > -1) &&
      wasInitialized() && resize > 0) {
      // do something
   }
}
load more v
75%

If the In modal dialogs refactoring option is selected in the Refactorings area on the Code Editing page of the Settings/Preferences dialog Ctrl+Alt+S, IntelliJ IDEA opens the Extract Variable dialog for this refactoring.,When you deselect one of the parameters in the dialog, the corresponding local values will be used instead. ,In the editor, select an expression or its part that you want to extract. You can also position the caret within the expression, in this case IntelliJ IDEA offers you a list of potential code selections.,Alternatively, from the context menu in the editor, select Refactor | Refactor This Ctrl+Alt+Shift+T, and select Functional Variable.

Starting with Java 1.8 and later versions, IntelliJ IDEA also lets you extract a functional type variable.

If your Java version supports the pattern matching (Java 14 preview or higher) and you are extracting a cast expression under the instanceof check, IntelliJ IDEA may introduce a pattern variable at that instanceof check instead of a normal local variable. Also, you can inline pattern variable since the Java 14 version. In this case, all the occurrences will be replaced with old-style cast expression.

instanceof

Starting with Java 1.8 and later versions, IntelliJ IDEA also lets you extract a functional type variable.

If your Java version supports the pattern matching (Java 14 preview or higher) and you are extracting a cast expression under the instanceof check, IntelliJ IDEA may introduce a pattern variable at that instanceof check instead of a normal local variable. Also, you can inline pattern variable since the Java 14 version. In this case, all the occurrences will be replaced with old-style cast expression.

instanceof
load more v
40%

It is possible to retrieve specific characters from a string variable.,How-to: VarSearch - Search & replace part of a variable. How-to: strlen.cmd - Get string length. PowerShell equivalent: Substring() - Return part of a longer string. , Examples The variable _test is used for all the following examples:,start_index Defines the starting point for the string returned, for positive numbers this is the number of characters skipped. A negative number will count backwards from the end of the string.

It is possible to retrieve specific characters from a string variable.

Syntax
   %
   variable: ~start_index %
   %
   variable: ~start_index, end_index %

   This can include negative numbers:

   %
   variable: ~start_index, -end_index %
   %
   variable: ~-start_index, end_index %
   %
   variable: ~-start_index, -end_index %
load more v
22%

Text or pattern that marks the start position of the text to extract, specified as one of the following:,Text or pattern that marks the end position of the text to extract, specified as one of the following:,Cell array of character vectors,Create string arrays and select substrings between start and end positions that are specified as numbers.

str = "The quick brown fox"
load more v

Other "extract-string" queries related to "How to extract specific variables from a string?"