Menu
  • HOME
  • TAGS

C# IEnumerable and string[]

c#,arrays,string,split,ienumerable

You have to use ToArray() method: string[] result = "bobjoecat".SplitBy(3).ToArray(); // [bob, joe, cat] You can implicitly convert Array to IEnumerable but cannot do it vice versa. ...

TypeError when split converting string to integer

python,string,split,integer,type-conversion

The invalid syntax comes from - self.input.value1=(int)word In python, the casting is not the same as in C/C++/Java , instead of using (datetype)variable you have to use datatype(variable) , though that is only for primitive datatypes. For other datatypes, you do not need casting, as python is a dynamically typed...

Split and Loop in java 8

java,split,java-8

Here's Java-8 solution: static void getResponse(String input, int level) { Stream.iterate(input, str -> { int pos = str.lastIndexOf('.'); return pos == -1 ? "" : str.substring(0, pos); }).limit(level+1).forEach(System.out::println); } If you know for sure that level does not exceed the number of dots, you can omit the check: static void...

why split() produces extra , after sets limit -1

java,regex,split

First you have unnecessary escaping inside your character class. Your regex is same as: String pattern = "[(?=)]"; Now, you are getting an empty result because ( is the very first character in the string and split at 0th position will indeed cause an empty string. To avoid that result...

Return splitted value

java,regex,split,return-value

How about first split by [ and then split by ] String str = "[#FF0000]red[#0000FF]blue"; String[] ss = str.split("\\["); String[] sRe = Arrays.copyOfRange(ss, 1, ss.length); for (String s : sRe) { System.out.println(s.split("\\]")[0]); System.out.println(s.split("\\]")[1]); } ...

R split vector with jumps

r,vector,split

Is this what you are looking for? full_seq <- 1:100 mysize <- 10 myjump <- 4 myseq <- seq(from=1, to=length(full_seq), by=myjump+mysize-1) full_splitted2 <- c() for (i in myseq) { if ((i+mysize-1) <= length(full_seq)) { full_splitted2 <- c(full_splitted2, full_seq[i:(i+mysize-1)]) } } full_splitted2 <- matrix(full_splitted2, ncol=mysize, byrow=TRUE) full_splitted2: [1,] 1 2 3...

Talend JSON structure

json,mongodb,split,tree,talend

For those who are interrested, I solved this issue by creating my own MongoDBOuput in a tJavaRow. In this way, I am more able to control the creation of my JSON schema. For example (in a tJavaRow): /*Get the MongoDB connection*/ DB db = (DB)globalMap.get("db_tMongoDBConnection_1"); /*Get the collection*/ DBCollection coll...

HTML help for mouseover split button image

image,split,mouseover

I placed two buttons in the same span and used CSS to align them together. For example: <span class="x-split-button"> <button class="x-button x-button-main"> About Ron</button> <button class="x-button x-button-main">About Cori</button> </span> I have included the codepen so you can see the code and the DEMO...

how to split a number without losing other same characters in Java

java,regex,split

You need to use word boundaries. string.split("\\b142\\b|\\D+"); OR Do replace and then split. string.replaceAll("\\b142\\b|[\\[\\]]", "").split(","); ...

Python Split files into multiple smaller files

python,file,split

Round-robin works and is easy: with open('myfile.txt') as infp: files = [open('%d.txt' % i, 'w') for i in range(number_of_files)] for i, line in enumerate(infp): files[i % number_of_files].write(line) for f in files: f.close() ...

Regex to split string by whitespace OR minus signs in C#

regex,string,split

Just split according to the below regex. @"\s+|(?<!\s)(?=-)" DEMO ie, string[] split = Regex.Split(input_str, @"\s+|(?<!\s)(?=-)"); ...

Splitting a floating point number into a sum of two other numbers, without rounding errors

split,floating-point,floating-accuracy

(using double-precision for the examples) I was wondering if it is possible to split somehow x = (I-1.0) + (f + 1.0), namely without floating point rounding error. There is no chance of obtaining such a split for all values. Take 0x1.0p-60, the integral part of which is 0.0 and...

Split a list into chunks determined by a separator

python,split

The usual approach for collecting contiguous chunks is to use itertools.groupby, for example: >>> from itertools import groupby >>> blist = ['item1', 'item2', 'item3', '/', 'item4', 'item5', 'item6', '/'] >>> chunks = (list(g) for k,g in groupby(blist, key=lambda x: x != '/') if k) >>> for chunk in chunks: ......

Split rows that have multiline text and single line text

excel,vba,excel-vba,split

This is a fairly interesting question and something I have seen variations of before. I went ahead and wrote up a general solution for it since it seems like a useful bit of code to keep for myself. There are pretty much only two assumptions I make about the data:...

How do I isolate the text between 2 delimiters on the left and 7 delimiters on the right in Python?

python,regex,string,split

You can use python's built-in csv module to do this. j = next(csv.reader([string])); Now j is each item delimited by a , and will include commas if the value is wrapped in ". See j[2]....

Word count not working when entering new line

c#,split,newline

txtReader.ReadLine(); strips your newline away. From the msdn: The string that is returned does not contain the terminating carriage return or line feed. so you have to add it manually (or just add a space) textLine = textLine + txtReader.ReadLine() + " "; consider using the StringBuilder class for repeated...

Count the number of consecutive pairs in a vector

r,table,count,split,categories

All consecutive pairs can be represented by two parallel vectors, omitting the last or the first observation x <- V[-length(V)] y <- V[-1] and then cross-tabulating these > xtabs(~ x + y) y x -1 1 -1 7 1 1 0 1 or in slightly different form > as.data.frame(xtabs(~x+y)) x...

Complex string splitting

c#,regex,string,parsing,split

There are more than enough splitting answers already, so here is another approach. If your input represents a tree structure, why not parse it to a tree? The following code was automatically translated from VB.NET, but it should work as far as I tested it. using System; using System.Collections.Generic; using...

How to split a table in 4 groups?

sql,sql-server,split

I would use conditional aggregation with the modulo function: select max(case when seq % 4 = 1 then part_no end) as part_no_a, max(case when seq % 4 = 2 then part_no end) as part_no_b, max(case when seq % 4 = 3 then part_no end) as part_no_c, max(case when seq %...

Apache Hadoop pig SPLIT not working. Giving Error 1200

hadoop,split,apache-pig,latin

Kindly find the solution to the problem below along with basic explanation about SPLIT operator: The SPLIT operator is used to break a relation into two new relations. So you need to take care of both conditions , like IF and ELSE: For instance: IF(Something matches) then make Relation1, IF(NOT(something...

python splitting string twice

python,string,split,pair

You can use a list comprehension to do both splits at once and return a list of lists: >>> a = '{1;5}{2;7}{3;9}{4;8}' >>> [item.split(';') for item in a[1:-1].split('}{')] [['1', '5'], ['2', '7'], ['3', '9'], ['4', '8']] ...

Split Python dictionary into multiple keys, dividing the values equaly

python,dictionary,split

I'm not exactly sure how you want to name your "split" keys, but a generator function should be an easy way to achieve what you want. Look at this example, keeping in mind that the names of the keys are wrong. def gen(d): for k, v in d.items(): yield ('H'...

SPLIT using “ ” delimiter in Google Sheets won't always preserve period following number

regex,string,split,google-spreadsheet,string-split

This may get a little 'ugly' but see if this works: =ArrayFormula(iferror(REGEXEXTRACT(" "&A1:A,"^"&REPT("\s+[^\s]+",COLUMN(OFFSET(A1,,,1,6))-1)&"\s+([^\s]+)"))) 6 in the offset denotes the (maximum) number of columns/groups that are outputted. as this is an arrayformula, no 'dragging down' is needed. ...

String split after a number and symbol

java,string,split

UPDATE After reading your question again, knowing that your Strings are in the format "ZZZ-numbers-Strings" and you want everything after "ZZZ-numbers-" Then you can do a split with a regex pattern of "ZZZ-\d+-". This will result in a 2-element array and you want the results at index 1. public static...

In a MySQL select statement, can I split a text column and then sum the parts as floats?

mysql,select,casting,split

You may have to define your own function.Here is an example I just tested, hope it is helpful to you(BTW: It is not advisable to implement such kind of functions in mysql. Maybe it is better to let the application servers to compute it instead of mysql :)). DELIMITER $$...

Regex match commas after a closing parentheses

javascript,regex,split

Your logic is backwards. (?=...) is a look-ahead group, not a look-behind. This means that s1.split(/(?=[\]\)]),/); matches only if the next character is simultaneously ] or ) and ,, which is impossible. Try this instead: s1.split(/,(?=[\[\(])/); ...

In R: get multiple rows by splitting a column using tidyr and reshape2

r,split,reshape2,tidyr

Try library(splitstackshape) cSplit(data, 'B', ',', 'long') Or using base R lst <- setNames(strsplit(as.character(data$B), ','), data$A) stack(lst) Or library(tidyr) unnest(lst,A) ...

Convert timestamp in HH:TT:SS format to seconds

python,python-2.7,split,timedelta,python-datetime

You can use totalseconds() from datetime.timedelta In [4]: t = time.strptime('00:01:25','%H:%M:%S') In [5]: datetime.timedelta(hours=t.tm_hour,minutes=t.tm_min,seconds=t.tm_sec).total_seconds() Out[5]: 85.0 For your example: In [14]: t1='00:01:25' In [15]: t2='00:01:10' In [17]: t1 = time.strptime(t1,'%H:%M:%S') In [18]: t2 = time.strptime(t2,'%H:%M:%S') In [22]:...

Java Read Text file with condition

java,split,bufferedreader

Something like: line = it.nextLine(); if (line.contains("specific string")) continue; test = StringUtils.split(line,(",")); Why are you using StringUtils to split a line? The String class supports a split(...) method. I suggest you read the String API for basic functionality....

Python Split Array use For Loop to Mean every split and put it back together

python,arrays,for-loop,split

Is this what you are after? import numpy as np Rxx = np.arange(100) epochs = 10 Rxx_mean = [] epoch_Rxx = np.array_split(Rxx,epochs) for i in range(0,epochs): Rxx_mean.append(np.mean(epoch_Rxx[i])) print Rxx_mean ...

Splitting Python List

list,python-2.7,split

In [18]: L = [(55, 22), (66, 33), (77, 44)] In [19]: a,b = zip(*L) In [20]: a Out[20]: (55, 66, 77) In [21]: b Out[21]: (22, 33, 44) ...

Split Variable and insert NA's in between

r,variables,split,data.frame

Judging by the OPs answer, "var" is a string, like: var <- c("3, 4, 5", "2, 4, 5", "2, 4", "1, 4, 5") If that is the case, you can consider cSplit_e from my "splitstackshape" package: library(splitstackshape) cSplit_e(data.frame(var), "var", ",", mode = "value", drop = TRUE) # var_1 var_2 var_3...

Powershell Split a file name

powershell,split,get-childitem

The result of -split is an array. You only want one field not both (which you get when you use $test0. Try $test0[0]. Or use a more appropriate function for this: $shortnom = $_ -replace ".out$","" or (since $_ is an IO.FileInfo object just use its BaseName property): write-host $_.basename...

Using split method to store values in HashMap

java,string,split,hashmap

What you seem to be looking is for each data like "(number,[1 OR X OR 2])" in text map.put(number, value) You can easily do it with Pattern/Matcher. So you need code like Map<String,String> map = new HashMap<>(); Pattern p = Pattern.compile(regex); Matcher m = p.matcher(data); while(m.find()){ map.put(m.group("number"), m.group("value")); } Your...

Turn comma seperated string into an array [duplicate]

jquery,arrays,split,comma

Use following method to get the selected options as comma-separated text: $('select').multipleSelect('getSelects', 'text'); To get selected option values as comma-separated string: $("select").multipleSelect("getSelects"); Docs: http://wenzhixin.net.cn/p/multiple-select/docs/#methods...

Split string in macro

c++,string,split,macros

You can just change your macros so that it will accept two parameters: the namespace name and the class name. Something like #define BASICTYPE_TRAITS(namespaceName, className) \ template <> \ struct DDSTraits<namespaceName::className> \ { \ using TypeSupportImpl = namespaceName::className##Impl; \ using TypeSupport_var = namespaceName::className##TypeSupport; \ }; template <typename T> struct BASICTYPE_TRAITS...

Split the strings into two parts Python

python,string,split

I guess that's what you wanted row[1:3] = row[14].split('/') ...

Creating new columns by splitting a variable into many variables (in R)

r,string,split,data.frame

This will work. First let's build the data. values <- paste0("0000000", 1:4) library(data.table) dt <- data.table(val = sample(values, 10, replace = TRUE)) A for loop is enough to define the new columns. for(level_var in dt[, unique(val)]){ dt[, eval(level_var) := ifelse(val == level_var, level_var, 0)] } ...

Escape / in .split()

javascript,regex,split

What this does is split on either " , " or " /" (note the space characters: space comma space and space forward slash). Your regular expression is absolutely fine if that's what you're intending to replace on. Here's a Regexper visualisation: Update There are no spaces in your string...

Python, splitting strings on middle characters with overlapping matches using regex

python,regex,split

I am posting this as an answer mainly not to leave the question answered in the case someone stumbles here in the future and since I've managed to reach the desired behaviour, albeit probably not in a very pythonic way, this might be useful as a starting point from someone...

Split the string from character and that character I don't want remove

javascript,regex,string,split

You can try this: var str = "Hello word" var ary = str.split(/(o)/)); //ary = ['hell', 'o' , ' w', 'o','rd']; ...

Split string between words and quotation marks

java,regex,split

You forget to include the ",comma before "game" and also you need to remove the extra colon after display_name display_name\":\"([^\"]*)\",\"game\" or \"display_name\":\"([^\"]*)\",\"game\" Now, print the group index 1. DEMO Matcher m = Pattern.compile("\"display_name\":\"([^\"]*)\",\"game\"").matcher(str); while(m.find()) { System.out.println(m.group(1)) } ...

Split string with comma delimiter but not if it is a currency value using C#

c#,regex,split

Just giving a non-regex answer for some variety. You could do the following: String[] MySplit(String str) { bool currency = false; char[] chars = str.ToCharArray(); for(int i = 0; i < str.Length(); ++i) { if(chars[i] == '$') currency=true; else if(currency && chars[i] == ',') { chars[i] = '.'; currency =...

How can I populate comboboxes from arrays?

c#,arrays,wpf,combobox,split

The variables array1 and array2 only exist inside your function scope. You meant to use cNames and cPhoneNumbers....

raw_input multiple inputs around strings

python,split,raw-input

Your code is not wrong. It actually works: >>> x1,x2,x3,x4 = 'xyuv' >>> a1, a2, a3, a4 = raw_input("("+x1+", "+x2+") to ("+x3+", "+x4+")").split() (x, y) to (u, v)1 2 3 4 >>> a1 '1' >>> a2 '2' >>> a3 '3' >>> a4 '4' However: the output (a1,a2,a3,a4) are strings. it...

Split Cell by Numbers Within Cell

excel,vba,split,cells

I was able to properly split the values using the following: If i.Value Like "*on Mission*" Then x = Split(i, " ") For y = 0 To UBound(x) i.Offset(0, y + 1).Value = x(y) Next y End If ...

Splitting a text file

python,text,split

This uses a different approach to yours. I have set the maximum size for each file to be 1000 bytes for testing purposes: import glob import os dname = './gash' # directory name unit_size = 1000 # maximum file size for fname in glob.iglob("%s/*" % dname): with open(fname, 'rb') as...

javascript split or slice?

javascript,split,slice

I would think that split is likely to be the best approach: var segments = currentUser.split(' '); var firstName = segments[0]; var lastName = segments[segments.length - 1]; var middleName = segments.length === 3 ? segments[1] : undefined; Here, firstName and lastName work regardless of the length of the array, or...

perl split to grab time in the string

perl,split

my $secs = 0; while ($output =~ /running time\s+(?:(\d+):)?(\d+(?:\.\d+)?)/g) { $secs += $1*60 if $1; $secs += $2; } ...

Splitting array in three different arrays of maximum three elements [duplicate]

arrays,ruby,split

Try this... Using Enumerable#each_slice to slice array x value array = [12, 13, 14, 18, 17, 19, 30, 23] array.each_slice(3) array.each_slice(3).to_a ...

R: how to split list into AM/PM

r,filter,split

You can use split split(df1, grepl('PM', df1$StartTime)) If you need to get a data.frame with two columns lst <- split(df1$StartTime, grepl('PM', df1$StartTime)) setNames(data.frame(lapply(lst, `length<-`, max(lengths(lst)))), c('AM', 'PM')) # AM PM #1 10:22 AM 8:37 PM #2 7:10 AM 3:58 PM #3 10:59 AM 2:48 PM #4 <NA> 6:33 PM Or...

split string in uppercase and camel case halves

regex,string,split

How about: ^([A-Z]+(?: [A-Z]+)+) (.*?)$ You'll have the uppercase words in group 1 and the rest in group 2 If you want to deal with any language: ^(\p{Lu}+(?: \p{Lu}+)+) (.*?)$ ...

How to split data monthly in R

r,data,split

You can use dplyr for this: df %>% mutate(new.date = cut.Date(as.Date(Date, format = '%Y-%m-%d'), "month")) %>% group_by(new.date) %>% summarise(count = n()) mutate will create a new column with cutted dates, group_by by month and summarise will count the number of entries. Also, if you need year and abbreviation month, just...

Display first Word in String with Ruby

ruby-on-rails,ruby,ruby-on-rails-4,split,string-split

Short and readable: name = "Obama Barack Hussein" puts "#{name.partition(" ").first} - #{name.partition(" ").last}" # Obama - Barack Hussein and if the order of the first and lastname is reversed name = "Barack Hussein Obama" puts "#{name.rpartition(" ").last} - #{name.rpartition(" ").first}" # Obama - Barack Hussein ...

How to extract specfic data from lines in a text file and output to a new text file using C#

c#,regex,split

Just a straightforward implementation: string workingDirectory = @"c:\"; var days = new[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; var writers = new Dictionary<string, StreamWriter>(); using (StreamReader sr = new StreamReader(workingDirectory + "data.csv")) { string line; while ((line = sr.ReadLine()) != null) { var items = line.Split(new[] {...

How to write regex for this javascript string

javascript,regex,split,string-split

You should use the ability of split to split on regular expressions and then keep them in the results. To do this, simply put a capturing group in the regexp. In your case, you will "split" on things in double quote marks: pieces = test.split(/(".*?")/) ^^^^^^^ CAPTURE GROUP // ["",...

re.split return None in function but normaly works OK

python,python-3.x,split

Your function does not return a value so it returns None as all python functions that don't specify a return value do: def whois(k, i): k = str(k[i]) print (k) whois = subprocess.Popen(['whois', k], stdout=subprocess.PIPE, stderr=subprocess.PIPE) ou, err = whois.communicate() who = str(ou) print (who.find('NetName:')) who = re.split('NetName:', who)[1] who...

hadoop large file does not split

performance,hadoop,split,mapreduce

dfs.block.size is not alone playing a role and it's recommended not to change because it applies globally to HDFS. Split size in mapreduce is calculated by this formula max(mapred.min.split.size, min(mapred.max.split.size, dfs.block.size)) So you can set these properties in driver class as conf.setLong("mapred.max.split.size", maxSplitSize); conf.setLong("mapred.min.split.size", minSplitSize); Or in Config file...

How to split string on multiple delimiters keeping some delimiters?

php,regex,string,split,explode

Try this: $src='word1&word2 !word3 word4 &word5'; $arr=explode(' ',$src=preg_replace('/(?<=[\w])([&!])/',' $1',$src)); echo join('<br>',$arr); // present the result ... First change any occurence of a group consisting of a single character of class [&!] that is preceded by a 'word'-character into ' $1' (=itself, preceded with a blank) and then explode()the string using...

R - How to split all the varaibles from a dataframe?

r,table,split

You are most likely looking for sub or gsub, or possibly strsplit--but definitely not split: mydf[] <- lapply(mydf, function(x) { sub("\\|.*$", "", x) }) mydf ## X.V1 X.V2 X.V3 ## 1 toto peper tomato ## 2 toto peper ognion ## 3 toto ginger lemon ...

How to keep punctuation as a separate element in split_string in Prolog

string,split,prolog,swi-prolog,punctuation

"split_string" is not standard but, in the implementation I know, you can not. From the ECLIPSe manual: The string String is split at the separators, and any padding characters around the resulting sub-strings are removed. Neither the separators nor the padding characters occur in SubStrings. http://www.cs.uni-potsdam.de/wv/lehre/Material/Prolog/Eclipse-Doc/bips/kernel/stratom/split_string-4.html ** Addendum ** We...

Compare one string among multiple values in another string [closed]

java,regex,string,split,compare

You can use java 8 : final String firstString = "B"; final String secondString = "A,B,C,D,E"; if (Arrays.stream(secondString.split(",")).anyMatch(s -> s.equals(firstString))) { // match } This split the String on ",", and transform the result in a stream, then check if one of the values of the stream is equal to...

split string based on text qualifier regex java

java,regex,split

Probably easiest solution is not searching for place to split, but finding elements which you want to return. In your case these elements starts " ends with " have no " inside. So you try with something like String data = "\"1\",\"10411721\",\"MikeTison\",\"08/11/2009\",\"21/11/2009\",\"2800.00\",\"002934538\",\"051\",\"New York\",\"10411720-002\",\".\\Images\\b.jpg\",\".\\RTF\\b.rtf\""; Pattern p = Pattern.compile("\"([^\"]+)\""); Matcher m =...

How to use Split() method in Android

java,android,string,list,split

I suggest you to use Pattern and Matcher classes. The below regex will capture the text present inside curly braces and then it would add them to the list variable. String myString = "A=myPage{a1,b1,c1};B=myPage{a2,b2,c2};C=myPage{a3,b3,c3};"; List<String> list = new ArrayList<String>(); Matcher m = Pattern.compile("\\{([^{}]*)\\}").matcher(myString); while(m.find()) { list.add(m.group(1)); } System.out.println(list); ...

Extract last word from strings

split,google-spreadsheet,string-split

There are many way to do so. One is to split on spaces and discard what is not required. Another is with a formula such as conventional in Excel (count the spaces by comparing the length of the string in full and after substituting spaces with nothing) and feed that...

How do i split text to a different column or remove a text from the original column?

excel,vba,excel-vba,text,split

So test that : Sub SplitValues() Dim aSplit As Variant With ActiveSheet For I = 2 To Cells(.Rows.Count, "D").End(xlUp).Row aSplit = Split(Cells(I, "D"), " ", 2) 'Write in D and E columns (erase data already in D) Cells(I, "D") = aSplit(0) Cells(I, "E") = aSplit(1) 'Write in E and F...

str_split adding empty elements in array end when reading from file

php,arrays,string,split

The extra whitespace is a newline. Each row except the last technically contains all of the text contents you see, plus a newline. You can easily get rid of it by e.g. $string = rtrim(fgets($handle)); Also, fgets($fp); makes no sense since there's no variable $fp, should be fgets($handle); given your...

Merging text files based on headings.

c#,visual-studio-2010,visual-studio,visual-studio-2012,split

You should show us what code you already have, then ask how to approach the part that you cannot solve. I suggest you to store a list of headers, and a list or dictionary of rows. This way you could check if a header already exists. For example: using System;...

prolog misunderstanding. Split list into two list with even and odd positions. where is my mistake?

list,split,prolog

The answer by CapelliC is perfect. Just to explain: When you have a Prolog clause like this: foo([H|T], [H|Z]) :- foo(T, Z). which you then call like this: ?- foo([a,b,c], L). from: foo([H| T ], [H|Z]) with H = a, T = [b,c], L = [a|Z] call: foo([a|[b,c]], [a|Z]) which...

How is Guava Splitter.onPattern(..).split() different from String.split(..)?

java,regex,split,guava

You found a bug! System.out.println(s.split("abc82")); // [abc, 8] System.out.println(s.split("abc8")); // [abc] This is the method that Splitter uses to actually split Strings (Splitter.SplittingIterator::computeNext): @Override protected String computeNext() { /* * The returned string will be from the end of the last match to the * beginning of the next one....

python: splitting strings where numbers and letters meet (1234abcd-->1234, abcd)

python,string,list,split

You can use Regex for this. import re s = 'this1234is5678it' re.split('(\d+)',s) Running example http://ideone.com/JsSScE Outputs ['this', '1234', 'is', '5678', 'it'] Update Steve Rumbalski mentioned in the comment the importance of the parenthesis in the regex. He quotes from the documentation: If capturing parentheses are used in pattern, then the...

Split string in AWK using multi-character delimiter

bash,awk,split

Since DEL is your shell variable, you should be using something like: info1=$(echo $STR | awk -v delimeter="$DEL" '{split($0,a,delimeter)} END{print a[1]}') ...

Python - Split string of numeric values with unknown delimiters

python,regex,string,split

I would like to split on any number of consecutive spaces, tabs, and commas. You could use re.split() to split by a regular expression. >>> import re >>> s = '0 0 .1 .05 .05 0. 0. .01' >>> re.split(r'[\s,]+', s) ['0', '0', '.1', '.05', '.05', '0.', '0.', '.01']...

PHP split or explode string on tag

php,regex,split,html-parsing,explode

You are in the right path. You have to set the flag PREG_SPLIT_DELIM_CAPTURE in this way: $array = preg_split('/(<img .*>)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE); With multiple tag edited properly the regex: $string = 'Text <img src="hello.png" > hello <img src="bye.png" /> other text.'; $array = preg_split('/(<img[^>]+\>)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE); This will...

Excel VBA Macro to get the substring of text before semicolon

excel,vba,excel-vba,split,substring

If you one use Split function, you will love it -> https://msdn.microsoft.com/en-us/library/6x627e5f%28v=vs.90%29.aspx Look for this example: Sub TestSplit() Dim String1 As String Dim Arr1 As Variant String1 = "TL-18273982; 10MM" Arr1 = Split(String1, ";") Debug.Print "TEST1: String1=" & String1 Debug.Print "TEST1: Arr1(0)=" & Arr1(0) Debug.Print "TEST1: Arr1(1)=" & Arr1(1) String1...

Create an array-of-arrays from an array's elements

php,arrays,split

You can use array_chunk() Documentation: http://php.net/manual/en/function.array-chunk.php It will split an array into a multi-demential array of "chunks." For you, you want every chunk to be 1 variable in size. $Alphabet = array('a','b','c','d'); $Chunked = array_chunk($Alphabet, 1); // Chunk the Alphabet array in 1 size chunks print_r($Chunked); This will produce: Array...

Split by a comma that is not inside parentheses, skipping anything inside them

java,regex,string,split

Could not figure out a regex solution, but here's a non-regex solution. It involves parsing numbers (not in curly braces) before each comma (unless its the last number in the string) and parsing strings (in curly braces) until the closing curly brace of the group is found. If regex solution...

Need a complex regular expression to split on camel case and numbers

php,regex,split,preg-split

Just add the other cases as extra possiblities using |: $tests = array('FooBar', 'fooBar', 'Foobar', 'FooBar1', 'FooBAR', 'FooBARBaz', '1fooBar', '1FooBar', 'FOOBar'); foreach($tests as $test){ echo $test . " => " . split_camel_case($test) . "<br />"; } function split_camel_case($root){ return implode(' ', preg_split('/(?<=[a-z])(?![a-z])|(?<=[0-9])(?![0-9])|(?<=[A-Z])(?=[A-Z][a-z])/', $root, -1, PREG_SPLIT_NO_EMPTY)); } ...

How to parse/split a string?

java,string,parsing,split

This ought to do it: String string = "N,591;F\"Vendor Number\",86;F\"Vendor Name\",143;F\"Claim Number\",82;"; String[] s = string.split("\""); System.out.println(s[1]); System.out.println(s[3]); System.out.println(s[5]); Output: Vendor Number Vendor Name Claim Number If the number of column labels is not known, choose every alternate index....

undefined method `split' for nil:NilClass Rails

ruby-on-rails,ruby,split

undefined method split' for nil:NilClass` The error is because the life of last variable has ended in the if-else loop and you are trying to access last outside the if-else loop in this line number = last.split('-')[1].to_i. You need to tweak your code like this def generate_asset_number company =...

Python - Splitting a large string by number of delimiter occurrences

python,string,split

If you want to work with files instead of strings in memory, here is another answer. This version is written as a function that reads lines and immediately prints them out until the specified number of delimiters have been found (no extra memory needed to store the entire string). def...

Code need to split string AND remove unwanted characters

c#,asp.net,string,split,string-split

string [] arr = input.Replace("T23:00:00.000Z","").Split(new string[] {","},StringSplitOptions.None); ...

Powershell For Loop, Replace, Split, Regex Matches

regex,powershell,replace,split

Leveraging the power in PowerShell we can turn the output of pnputil into an object array that will make it much easier to parse the data you are looking for (since it appears you are looking for something specific). Each entry is a group of variables with a blank line...

Splitting a text line into separate lines from command line

text,split,command

Using tr actually was easier, as show in e.g. this question. Here's the command echo $PATH | tr ':' '\n' ...

Splitting at a specific point in PDFBox

pdf,split,pdfbox

One way to achieve the task, i.e. to split a page at a certain point (i.e. all content above a limit to be included and everything below to be excluded) would be to prepend a clip path. You can use this method: void clipPage(PDDocument document, PDPage page, BoundingBox clipBox) throws...

Split string using word but keep the word in each array index

java,regex,string,split

Change your code a little to use positive lookbehind. String[] stringArray = string.split("(?<=</xml>)"); O/P : <xml attributes>some xml code</xml> <xml attributes>some xml code</xml> <xml attributes>some xml code</xml> <xml attributes>some xml code</xml> ...

Splitting a document from a tm Corpus into multiple documents

regex,r,split,tm,text-analysis

You can use strsplit to split your document , then recreate the corpus again : Corpus(VectorSource( strsplit(as.character(documents[[1]]), ## coerce to character "I want to split after this line!!!", fixed=TRUE)[[1]])) ## use fixed=T since you have special ## characters in your separator To test this , we should first create a...

Split a string only by first space in python

python,string,split

Just pass the count as second parameter inside the split function. >>> s = "238 NEO Sports" >>> s.split(" ", 1) ['238', 'NEO Sports'] ...

Scala: Convert a csv string to Array

arrays,string,scala,split,scala-collections

Use split with -1 argument. string.split(",",-1) This behavior comes from Java (since Scala uses Java Strings). Here is the documentation directly out of Javadoc. ...

MySQL split a column out with ID

mysql,table,split

One method is to export the data and use another tool. If the strings are not too long, you can do something like this: create table common_name_frog as select f.id, substring_index(substring_index(common_name, ', ', n.n), ', ', -1) as Common_name from (select 1 as n union all select 2 union all...

Splitting a delimited file and storing into new column

python,split

You're pretty much there already! A few more lines after new = row[4].split(",") are all you need. for i in range(len(new), 4): new.append('') newrow = row[0:4] + new + row[5:] print('|'.join(newrow)) Edit 2: addressing your comments below in the simplest way possible, just loop through it twice, looking for the...

Split by a word (case insensitive)

python,regex,string,split

You can use the re.split function with the re.IGNORECASE flag (or re.I for short): >>> import re >>> test = "hI MY NAME iS FoO bar" >>> re.split("foo", test, flags=re.IGNORECASE) ['hI MY NAME iS ', ' bar'] >>> ...

split signal right before local minima in Numpy

numpy,split

I'm not sure the accepted answer will generally do what you show on your graphs. I certainly can't get it to produce the correct answer! Generally you will always get alternating maxima and minima with edge cases of none of one or both. You need to look at all the...

Split array into another array

c#,arrays,split

you can use Split and SelectMany var result = Array.SelectMany(x => x.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)).ToArray(); ...