w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Selectively deleting commas and splitting strings
A silly (but functional) answer: inquotes=false; keep=true(1,length(txt)); for v=1:length(txt) if (txt(v)=='"') inquotes=~inquotes; elseif (txt(v)==',' && inquotes) keep(v)=false; end end txt=txt(keep); tt=strsplit(txt,','); This will, if you are in quotes, remove the commas so that you can use strsplit. That is what I understood you want to do, correct?

Categories : Regex

Regular Expression for Comma Based Splitting Ignoring Commas inside Quotes
You need to use the split(java.lang.String, int) method Your code would then look like: String str = "20Y-62-27412,20Y6227412NK,BRACKET,101H,00D505060,H664374,06/25/2013,1,,"; String[] rowData = str.split(",(?=([^"]*"[^"]*")*[^"]*$)", -1);

Categories : Java

Javascript splitting string using only last splitting parameter
To expand upon elclanrs comment: function getParts(str) { var temp = str.split('.').slice(-3) // grabs the last 3 elements return { tld_parts : [temp[1],temp[2]].join("."), sld_parts : temp[0] } } getParts("foo.bar.baz.co.uk") would return { tld_parts : "co.uk", sld_parts : "baz" } and getParts("i.got.99.terms.but.a.bit.aint.one.co.uk") would return { tld_parts : "co.uk", sld_parts : "one" }

Categories : Javascript

Parsing a comma-delimited string that contains string items that contain commas
I'll suggest using strtok using comma as the field separator. However, if the first character in the string is a double quote, you should use " as the field separator. If I assume that what you showed is a struct, I wrote the code in C to print the output on separate lines: #include <stdio.h> #include <string.h> int main() { char str[] = "0,1,"foo","blue,yellow,red",27"; printf ( "Input string: %s ", str ); char * substr; char * str_itr = str; char comma[] = ","; char quote[] = """; substr = strtok ( str_itr, comma ); if ( substr ) printf ( "%s ", substr ); substr = strtok ( NULL, comma ); if ( substr ) printf ( "%s ", substr ); substr = strtok ( NULL, quote ); if ( substr ) printf ( "%s ", substr

Categories : String

Hashing a string between two integers with a good distribution (Uniform Hash)
Hogan gave in comment a link to several hash implementation in javascript. It turns out that the most simple (and probably the worst one quality wise for hashing in the standart int range) is the most appropriate: function nameToColor(name) { var colors = ['red', 'blue', 'green', 'purple', 'orange', 'darkred', 'darkblue', 'darkgreen', 'cadetblue', 'darkpurple']; var hash = hashStr(name); var index = hash % colors.length; return colors[index]; } //very simple hash function hashStr(str) { var hash = 0; for (var i = 0; i < str.length; i++) { var charCode = str.charCodeAt(i); hash += charCode; } return hash; } I t

Categories : Javascript

string to type function, template specialization to make call uniform
You may want something like that: #include <string> #include <sstream> namespace details { template <typename T> struct stringToTypeImpl { void operator () (std::stringstream& ss, T& t) const { ss >> t; } }; // And some specializations template <typename T, int W, int H> struct stringToTypeImpl<Eigen::Matrix<T, W, H> > { void operator () (std::stringstream& ss, Eigen::Matrix<T, W, H>& t) const { for (int j = 0; j != H; ++j) { for (int i = 0; i != W; ++i) { stringToTypeImpl<T>()(ss, t(i, j)); //ss >> t(i, j); } } } } // ... } template <

Categories : C++

How to remove unwanted commas from a string?
Try this: $str = preg_replace('/,{2,}/', ',', trim($str, ',')); The trim will remove starting and trailing commas, while the preg_replace will remove duplicate ones. See it in action! Also, as @Spudley suggested, the regex /,{2,}/ could be replaced with /,,+/ and it would work too. EDIT: If there are spaces between commas, you may try adding the following line after the one above: $str = implode(',', array_map('trim', explode(',', $str)))

Categories : PHP

Only strip commas surrounded by numbers in a string
It sounds like you want to use a regular expression: string rawtext = Regex.Replace(nextLine, @"(d),(d)", "$1$2"); Or this equivalent pattern: string rawtext = Regex.Replace(input, @"(?<=d),(?=d)", "");

Categories : C#

Convert ArrayList Contents to String with Commas
Just use ArrayList#toString(): public void getOptionsText() { String OptionsText = ListOptions.toString(); Options.setText(OptionsText.substring(1, OptionsText.length-1); }

Categories : Java

Ensure splitting comma separated string with numbers in string
If the source string cannot be changed I would split on letters: v.Split(new[] {'A', 'B', 'C', 'D'}); or v.Split(new[] {"A:", "B:", "C:", "D:"}); and than tidied up the resulting parts.

Categories : C#

splitting string based on case insensitive sub-string
You can use NSRange range = [string rangeOfString:@" and " options: NSCaseInsensitiveSearch]; to find the location of the separating string in a case-insensitive way, and then extract the first and last part with if (range.location != NSNotFound) { NSString *first = [string substringToIndex:range.location]; NSString *last = [string substringFromIndex:(range.location + range.length)]; } else { // separator not found ... }

Categories : Iphone

regex ensure that a string only contains pipes, numbers and /or commas,
Try following: function ensure($str) { return (bool) preg_match('/^[d|,]+$/', $str); } var_dump(ensure('1|2,2|3')); var_dump(ensure('1|2')); var_dump(ensure('16|2')); var_dump(ensure('bob')); var_dump(ensure('bob|yes,no')); var_dump(ensure('')); prints bool(true) bool(true) bool(true) bool(false) bool(false) bool(false)

Categories : PHP

How does java recognizes anything in inverted commas as a string object?
"abc" is a String literal , defined by the specifications of the language. Refer JLS 3.10.5: A string literal consists of zero or more characters enclosed in double quotes. Characters may be represented by escape sequences (§3.10.6) - one escape sequence for characters in the range U+0000 to U+FFFF, two escape sequences for the UTF-16 surrogate code units of characters in the range U+010000 to U+10FFFF. Suggested Reading: Difference between string object and string literal. Java String Pool Also , read String is Really Special: String literals are stored in a common pool. This facilitates sharing of storage for strings with the same contents to conserve storage. String objects allocated via new operator are stored in the heap, and there is no sharing of storage for the sam

Categories : Java

Removing commas and empty tags from a string using regex
Firstly: Have you checked whether is Akismet not already doing this? I would very much suspect it already does all this processing (and more), so you don't actually need to. Anyway, assuming this is bbcode, and thus the relevant tags will be for bold/italic/underline, you can replace them with: TextForAkismet = rereplace( TextForAkismet , '[([biu])][/1]' , '' , 'all' ) If there are other empty tags you want to remove, simply update the captured group (the bit in parentheses) as appropriate. To also cater for potentially attributes (but still an empty tag), a quick and dirty way is to use [^]]* after the tag name (outside the captured group). '[([biu]|img|url)[^]]*][/1]' Depending on the dialect of bbcode you're working with, you may need to handle quoted brackets which would need

Categories : Regex

Binding String Format Number Commas & No Decimal Places
You almost had it... how about trying this: {Binding ANLA, StringFormat='0,0.'} Please note that this will round the number to the nearest integer.

Categories : Wpf

String missed while splitting a string in python
One of these might help: packet='''0000 xx ff 3a 31 89 c3 ff 00 58 00 20 41 aa aa 03 00 >.:1....X. A.... 0010 02 de 01 11 05 00 02 00 00 ff 3c ff 00 00 34 2d .........K<....- 0020 00 44 00 00 00 00 00 00 0a x3 00 01 00 60 00 00 ................ 0030 00 00 89 70 62 00 02 00 00 76 98 05 8b ..i.b....v...''' # Using a generator expression result = ' '.join(' '.join(line[5:55].split()) for line in packet.splitlines()) print 'xx ff' in result # true print 'x3' in result # true print '72' in result # false # Using a loop result = [] for line in packet.splitlines(): result.extend(line[5:55].split()) result = ' '.join(result) print 'xx ff' in result # true print 'x3' in result # true print '72' in result # false

Categories : Python

Remove commas in a string, surrounded by a comma and double quotes / Python
If all you need to do is replace commas with the @ character you should look into doing a str_replace rather than regex. str_a = "Completely renovated in 2009, the 2-star Superior Hotel Ibis Berlin Messe, with its 168 air-conditioned rooms, is located right next to Berlin's ICC and exhibition center. All rooms have Wi-Fi, and you can surf the Internet free of charge at two iPoint-PCs in the lobby. We provide a 24-hour bar, snacks and reception service. Enjoy our breakfast buffet from 4am to 12pm on the 8th floor, where you have a fantastic view across Berlin. You will find free car parking directly next to the hotel." str_a = str_a.replace('","', '@') #commas inside double quotes str_a = str_a.replace(',', '@') #replace just commas print str_a Edit: Alternatively you could make a list

Categories : Python

Regex string for Sublime Text to find email address between two commas
I'm not familiar with the ruby language, but a regex that finds what you want is: w+@w+.w+ with the . maybe unneeded (depending on language). a perl one-liner that does the exact thing: perl -pi -e 's/w+@w+.w+/<your new email here>/g' <csv file here> note make sure you use @ in the enw email in the one liner i wrote, meaning new_email@server.com

Categories : Ruby

How to add or insert ' (single quotes) for every string in a list in which strings are seperated by commas using Java
1) Iterate the list (for/while) 2) For each elements of list append ' ',.(Hint: use append() on StringBuilder 3) Truncate /substring the list to remove the last , added (Hint: use substring on String class)

Categories : Java

Splitting GET string
You can use preg_split with this pattern: &(?=ident) $result = preg_split('~&(?=ident)~', $yourstring); regex detail: &(?=ident) means & followed by ident (?=..) is a lookahead assertion that performs only a check but match nothing. Or using preg_match_all: preg_match_all('~(?<=^|&)[^&]+&[^&]+&[^&]+(?=&|$)~', $yourstring, &matches); $result = $matches[0]; pattern detail: (?<=..) is a lookbehind assertion (?<=^|&) means preceded by the begining of the string ^ or an ampersand. [^&]+ means all characters except the ampersand one or more times. (?=&|$) means followed by an ampersand or the end of the string $. Or you can use explode, and then a for loop: $items = explode('&', $yourstring); for ( $i=0; $i<si

Categories : PHP

SQL - Splitting a string into a new row
Heres a solution, I took some code from another website but cant remember whos and then modified it. I added some data to a temp table to show it works DECLARE @DATA TABLE (COL1 NVARCHAR(10), COL2 NVARCHAR(100)) DECLARE @RESULT TABLE (COL1 NVARCHAR(10),COL2 NVARCHAR(100)) DECLARE @COL1 NVARCHAR(10) DECLARE @COL2 NVARCHAR(10) INSERT INTO @DATA VALUES ( 'A001', 'A1;A2;A3') INSERT INTO @DATA VALUES ( 'B002', 'B1') INSERT INTO @DATA VALUES ( 'C003', 'C1;C2') INSERT INTO @DATA VALUES ( 'D004', 'D1;D2;D3;D4') INSERT INTO @DATA VALUES ( 'E005', 'E1') DECLARE CURDB CURSOR FOR SELECT * FROM @DATA OPEN CURDB FETCH NEXT FROM CURDB INTO @COL1, @COL2 WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @S varchar(max), @Split char(1), @X xml SELECT @S = @COL2, @Split = ';' SELECT @X = CO

Categories : SQL

Splitting up a string - php
You're trying to iterate over the string in your interior foreach. Try foreach ($result["response"] as $value) { $alternative[$i] = explode ("|", $value["list"]["synonyms"]); $i++; }

Categories : PHP

Tokenizing or Splitting String
I suppose you want to get the tokens {a, b, c, d} or {a, b, d}, so, it's very easy using StringTokenizer class. Look at this example: String exampleA = "a/b/c/d"; StringTokenizer tokens=new StringTokenizer(exampleA , "/"); while(tokens.hasMoreTokens()){ System.out.println(tokens.nextToken()); } You'll get: {a, b, c, d} And, for the second example: String exampleB = "a/b//d"; StringTokenizer tokens=new StringTokenizer(exampleB, "/"); while(tokens.hasMoreTokens()){ System.out.println(tokens.nextToken()); } You'll get: {a, b, d} I hope this is useful for you. Cheers!

Categories : Java

Getting in trouble while splitting a string in PHP
I can see that there are two new lines in your $var1, try this explode(" ", $var1); phpFiddle Demo

Categories : PHP

Splitting a string with delimiter in C++
Generally speaking, a string is a char pointer. So you should search for the first character in the delimeter, then check the very next character. Also in looking at your code I am not sure that while (0 != *str++) is doing what you think it is. I think you mean for it to be null terminated.

Categories : C++

Splitting a string of characters in vb.net
Use String.Split and Int32.Parse in this Linq query: Dim intArr = str.Split(","c).Select(Function(s) Int32.Parse(s)).ToArray() or, if you find the query-syntax easier: Dim ints = From str In str.Split(","c) Select Int32.Parse(str) dim intArr = ints.ToArray() here the old approach without Linq but correctly sized array: Dim strArr = str.Split(","c) Dim intArr(strArr.Length - 1) As Int32 For i As Int32 = 0 To strArr.Length - 1 intArr(i) = Int32.Parse(strArr(i)) Next

Categories : Dotnet

String splitting in the D language
Use split(line.idup); split is a template function, the return type depends on its argument. file.byLine.front returns a char[] which is also reused for performance reasons. So if you need the parts after the current loop iteration you have to do a dup or idup, whatever you need.

Categories : String

Splitting up a string based on csv
You should be able to read a csv, and get the single values with this code: string[] records = File.ReadAllLines(fileName); // read the file completely line by line // loop through all lines foreach (string record in records) { string[] fields = record.Split(splitChar); // reads all the single values per line. 'splitChar' should be the delimiter. }

Categories : C#

Perl - Splitting a string
To get the length of an array use scalar @nameList instead of @nameList.length. A typical for-loop uses the less-than operator when counting up, e.g.: for ( $to = 0; $to < scalar(@nameList); $to++ ) ... You should never use a post-increment unless you understand the side effects. I believe the following line: @nameList[$to] = @nameList[$to] . "_" . @nameList[$to++]; ... should be written as ... $nameList[$to] = $nameList[$to] . "_" . $nameList[$to + 1]; Finally the comparison you use should account for the boundary condition (because you refer to $to + 1 inside the loop): if( $to < (scalar(@nameList) - 1) ) { $nameList[ $to ] = $nameList[ $to ] . "_" . $nameList[ $to + 1 ]; }

Categories : Arrays

Splitting a string and picking a value
Just do: R = S.split('/')[2] to pick the third value. Usually when you split using / it is related to a file path. If this is the case you have the following shortcut: import os R = os.path.split(path)

Categories : Python

Splitting a string in C#, why is this not working?
Use something like this string[] separators = {@"v"}; string value = @"The objective for test.vVisionv* Deliver a test goalsv** Comprehensivev** Controlv* Alignment with cross-Equities strategyvApproachv*An acceleration"; string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);

Categories : C#

Splitting characters in string
You want to splice and join, not split: '-'.join(mystr[i:i+2] for i in xrange(0, len(mystr)-1)) You could also use itertools.islice and itertools.izip: '-'.join((a+b for a,b in itertools.izip(mystr, itertools.islice(mystr, 1, len(mystr)))))

Categories : Python

How do I keep the delimiters when splitting a Ruby string?
The most robust way to do this is with a Natural Language Processing library: Rails gem to break a paragraph into series of sentences You can also split in groups: @content.split(/(?+)|(.+)|(!+)/) After splitting into groups, you can join the sentence and delimiter. @content.split(/(?+)|(.+)|(!+)/).each_slice(2) {|slice| puts slice.join}

Categories : Ruby

C++ Splitting a string into strings and ints
I'm going to assume the order of ints and strings is unknown. You can exploit the conversion of cin to bool to decide whether you have detected an int or not. Basically, (cin >> intValue) (where intValue is an int) is an expression which returns true if the next few characters constitute a valid number that can fit into an int, and false otherwise. Same principle applies for other types such as string. These can be used in if-statements such as int intValue; if (cin >> intValue) { //evaluates to true or false // do something } else { // do something else } You can use this with a while-loop to parse your whole input, like so: vector<int> ints; //container to store ints vector<string> strings; //container to store ints while(true) { int intValue; string s

Categories : C++

Splitting String with split method
You need to escape ^ with cause ^ represents beginning of line in regex. See documention MedText.split("\^\^"); And here is the test on your string String test = "ilaç etkileşimleri: Antihistaminikler alkol ve antidepresanların etkilerinde artmaya yol açabilirken fenilpropanolamin'in b-adrenerjik blokerlerle beraber kullanılması. "+ "^^Endikasyonları: Grip ve soğuk algınlığına bağlı burun tıkanıklığı ve burun akıntısı, aksırma, burun ve boğazda kaşıntı, baş ağrısı, adale ağrısı, boğaz ağrısı, vücut kırıklığı, ateş, nezle, gözlerde sulanma ve kaşıntı gibi durumlarda kullanılır. "+ "^^Uyarılar/Önlemler: A-ferin forte tablet, sedasyona yol açabilir. Bu nedenle dikkat gerektiren makinalarda çalışanl

Categories : Java

splitting a string based on tab in the file
You can use regex here: >>> import re >>> strs = "foo bar spam" >>> re.split(r' +', strs) ['foo', 'bar', 'spam'] update: You can use str.rstrip to get rid of trailing ' ' and then apply regex. >>> yas = "yas bs cda " >>> re.split(r' +', yas.rstrip(' ')) ['yas', 'bs', 'cda']

Categories : Python

splitting the string as name, value pair in perl
Use JSON module for parsing json structures to perl use strict; use warnings; use JSON; my $json_text = q({ "errorcode": 0, "message": "Done", "login": [ { "session_timeout": "1800", "token": "1370907977", "sessionid": "##F7A7E49F7FCFF35D3F821201CBF2F7CB5937E4AC99BF2AF74B508A1C8B3F", "username": "" } ] }); my $href = decode_json($json_text); print $href->{errorcode}, $href->{message}, " ";

Categories : Perl

Abstract error when splitting a string
TStrings is an abstract class, and thats why you're getting abstract error. LBOMPartLine has to be declared as TStringList instead, which is descendant of TStrings class. Compiler warns you about instantiating a class that has abstract methods - I suggest that you don't ignore warnings and try to write proper code, without them. Also, class creation should be done outside of try/finally block: some_class := TSomeClass.Create; try .. finally some_class.Free; end;

Categories : String

Splitting string by spaces difficulty
Get rid of cin >> text; . That one consumes the first word of your input, reads it into text, and then you discard it by overwriting text in the next line.

Categories : C++

Splitting string selectively on spaces
You can parse your string using std::stringstream and std::getline #include <iostream> #include <sstream> #include <string> int main() { std::string text("move 3 "New Island" "South Afrika""); std::string command, count, country1, country2, temp; std::stringstream ss(text); ss >> command >> count; ss.str(""); ss << text; std::getline(ss, temp, '"'); std::getline(ss, country1, '"'); std::getline(ss, temp, '"'); std::getline(ss, country2, '"'); std::cout << command << ", " << count << ", " << country1 << ", " << country2 << std::endl; return 0; }

Categories : C++



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.