logo
down
shadow

String with comma-separated values and newlines: split values and create arrays for each newline


String with comma-separated values and newlines: split values and create arrays for each newline

Content Index :

String with comma-separated values and newlines: split values and create arrays for each newline
Tag : ruby , By : Nick Pegg
Date : November 24 2020, 01:01 AM

With these it helps I have a string like this (from a form submission):
s = "apple, banana\r\ncherries\r\n\r\ngrapes, blue berries \r\n\r\n \r\norange"
s.each_line.reject { |l| l =~ /^\s+$/ }.map { |l| l.strip.split(', ') }

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

XSLT 2.0 : Split a string into comma separated values


Tag : string , By : user185283
Date : March 29 2020, 07:55 AM
seems to work fine I am new to XSLT and have a requirement where in i have to manipulate a string as below. , Here is some XSLT/XPath 2.0 approach:
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:mf="http://example.com/mf"
  exclude-result-prefixes="xs mf"
  version="2.0">

  <xsl:function name="mf:sub-sequences" as="xs:string*">
    <xsl:param name="input" as="xs:string"/>
    <xsl:param name="min-length" as="xs:integer"/>
    <xsl:sequence select="reverse(
                            for $length in $min-length to string-length($input)
                            return substring($input, 1, $length)
                          )"/>
  </xsl:function>

  <xsl:template name="main">
    <xsl:variable name="s" select="'12345'"/>
    <xsl:value-of select="mf:sub-sequences($s, 2)" separator=","/>
  </xsl:template>

</xsl:stylesheet>

Accept either comma separated values or newline separated values


Tag : javascript , By : Andrew Mattie
Date : March 29 2020, 07:55 AM
I wish this help you I have this code: , You can use a regex in the split, like so:
'1,2\n3'.split(/[,\n]/)

String.split() - How to diferentiate between tab separated values and comma separated values?


Tag : java , By : kbrust
Date : March 29 2020, 07:55 AM
help you fix your problem line.split does not return null when the regular expression doesn't find any matches. Instead it returns an array with the whole line as the first and only element.
Therefore the first condition ais always true.

Split string in SQL for mixed and particular comma separated values?


Tag : sql , By : xie renhui
Date : March 29 2020, 07:55 AM
I hope this helps . Used a #Temp table to store the parsed results. Perhaps you can migrate into a cte
Declare @YourTable table (ID int,Data varchar(max))
Insert Into @YourTable values
(1,'abc,def'),
(2,'def,abc'),
(3,'def,ghi')

Select A.ID
      ,B.*
      ,ColName = 'Data'+cast(DENSE_RANK() over (Order By RetVal) as varchar(25))
Into #Temp
From @YourTable A
Cross Apply (
              Select RetSeq = Row_Number() over (Order By (Select null))
                    ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
              From (Select x = Cast('<x>'+ Replace(A.Data,',','</x><x>')+'</x>' as xml).query('.')) as A 
              Cross Apply x.nodes('x') AS B(i)
             ) B


Declare @SQL varchar(max)
Select  @SQL = Stuff((Select Distinct ',' + QuoteName(ColName) From #Temp For XML Path('')),1,1,'')   
Select  @SQL = 'Select ID,' + @SQL + ' 
                From (Select ID,ColName,RetVal From #Temp) A
                Pivot (max(RetVal) For ColName in (' + @SQL + ') ) p'

Exec(@SQL);
ID  Data1   Data2   Data3
1   abc     def     NULL
2   abc     def     NULL
3   NULL    def     ghi

Split values in string separated by both comma and a letter


Tag : cpp , By : KT.
Date : March 29 2020, 07:55 AM
Hope that helps Assuming the strings are sent as lines (with a new line character \n at the end).
typedef struct {
    int A = 0;
    int B = 0;
    int C = 0;
    int D = 0;
    int E = 0;
    int F = 0;
    char G = 0;
    int H = 0;
} Line;

typedef void (*LineHandler)(Line data);

bool line_parser(char c, LineHandler line_handler) {
    static Line data;
    static int value = 0;
    static byte state = 0;
    bool complete = false;

    // ignore the carriage return character
    if (c == '\r') return complete;

    if (state < 8) {
        if (isdigit(c)) {
            value = value*10 + c-'0';  // add the digit
        }
        else if (c == ',' || c == '\n') {
            // if a comma or end of line is found, save the value
            switch (state) {
                case 0: data.A = value; break;
                case 1: data.B = value; break;
                case 2: data.C = value; break;
                case 3: data.D = value; break;
                case 4: data.E = value; break;
                // the F and G are set when the letter is found
                case 7: data.H = value; break;
            }
            // advance the parsing state and reset the value
            state++;
            value = 0;
        }
        else if (state == 5 && isalpha(c)) { // if parsing the 6th number and a letter is found
            data.F = value; // save the 6th number
            data.G = c; // save the letter
            state += 2; // advance to parsing the 8th value
            value = 0; // reset the value
        }
        else
            state = 10; // unexpected character; stop the parser
    }
    if (c == '\n') {
        if (state == 8) {
            //got complete line
            line_handler(data);
            complete = true;
        }
        else {
            // parsing failed
        }
        // reset the parser
        value = 0;
        state = 0;
    }
    return complete;
}

void handle_line(Line data) {
    // just print out the data
    Serial.println("Line:");
    Serial.print("A = ");
    Serial.println(data.A);
    Serial.print("B = ");
    Serial.println(data.B);
    Serial.print("C = ");
    Serial.println(data.C);
    Serial.print("D = ");
    Serial.println(data.D);
    Serial.print("E = ");
    Serial.println(data.E);
    Serial.print("F = ");
    Serial.println(data.F);
    Serial.print("G = ");
    Serial.println(data.G);
    Serial.print("H = ");
    Serial.println(data.H);
    Serial.println();
}

void setup() {
    Serial.begin(115200);
}

void loop() {
    if (Serial.available()) {
        line_parser(Serial.read(), handle_line);
    }
}
54,125,11045,11,78,4H45
invalid line
11,22,33,44,55,66K88
30,30,20,10,50,50M20
Line:
A = 54
B = 125
C = 11045
D = 11
E = 78
F = 4
G = H
H = 45

Line:
A = 11
B = 22
C = 33
D = 44
E = 55
F = 66
G = K
H = 88

Line:
A = 30
B = 30
C = 20
D = 10
E = 50
F = 50
G = M
H = 20
Related Posts Related QUESTIONS :
  • aws-s3 and European Buckets
  • How to verify that "puts" has been called with a certain message?
  • Rack URL Mapping
  • Good and free Ruby editor for Windows?
  • Ruby TCPSocket doesn't notice it when server is killed
  • Merge a hash with the key/values of a string in ruby
  • Iterate through every file in one directory
  • How to validate SSL certificate chain in ruby with net/http
  • How can I upgrade my Ruby Gems to the latest version "safely"?
  • Reading a file N lines at a time in ruby
  • Package Ruby to a standalone Mac OS X application?
  • How can install sqlite-ruby on linux when sqlite3 is not in /usr/local?
  • Simple Serialization Faster Than JSON? (in Ruby)
  • Nokogiri Error: undefined method `radiobutton_with' - Why?
  • Ruby Pony alternative for Ruby 1.9?
  • How do I put an escape character (NOT "escaped" character) in a Ruby regex?
  • Lazy evaluation in Ruby
  • Net::HTTPResponse body as IO
  • Ruby DSL experiences?
  • Is there a way to return a method parameter names in ruby
  • Rack::Test not able to find web app cookie
  • rb_str_modify() equivalent in the Ruby language
  • How to make OSX application that just runs opens some file type and runs arbitrary Ruby code?
  • RVM Ruby 1.9.1 install can't locate zlib but its runtime and dev library are there
  • VSCode Style/PercentLiteralDelimiters rule not being respected in ruby files
  • What does it mean (and imply) that quicksort in Ruby is not stable?
  • Iv'e tried defining a function in ruby with constant parameter names, why does it return an error?
  • How to go through array of URLs using Curb
  • Ruby instance variables within class?
  • Capybara instance of "browser" for Page Object Model?
  • How to navigate to a link using page object gem?
  • undefined method `<' for true:TrueClass (NoMethodError)
  • AWS Inbound IP SSH Ranges to allow Capistrano deploy via Circle CI
  • During gem update I get permissions error for /usr/bin directory
  • Find element dict based on elements of a list
  • What to use instead of --no-ri for gem install?
  • Simple ruby script to process queue using multithreading throws Deadlock error?
  • How to sum values from csv file with Ruby
  • Is there a more elegant way of writing a while loop in Ruby where the array size is not known?
  • Why truncate when we had to pass a 'w' as an extra parameter to open in Ruby
  • Action on Unpermitted Parameters on production environment
  • Printing time remaining of the Time.now class to the console
  • Difference between {puts a} and {|a| puts a} in Ruby?
  • How to write a type signature for a block with Sorbet?
  • Creating a gem from a Capistrano task
  • Ruby spawn process, capturing STDOUT/STDERR, while behaving as if it were spawned regularly
  • RestClient post request in ruby on rails
  • Rubygems: You do not have permission to push to this gem
  • I have a number of questions about this (beginner) example code
  • Method cannot be called inside of a class
  • Why are both sig and T.let required for Sorbet to type check?
  • Would someone help me understand the Ruby manual's example of str.counts?
  • Very confused by this use of 'self'; 'parameter.method'
  • Ignoring cases in a string using .include?
  • Getting permission denied error when I run "gem install bundler"
  • Ruby conditions and defined? operator weird behavior
  • Can I pass the minus (-) or plus (+) sign as params into a method and use them in the method?
  • How could I stop these arrays from generating further numbers when one of the two have finished?
  • Comparing arrays within functions
  • Latest gem version not installing
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com