w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Python extracting substrings within brackets in a string
params = sent.split(id1)[1].split(")")[0].lstrip("(") print params That should do what you want. That being said, there are better ways to do this. You could store your items as key:value pairs using a dictionary for example.

Categories : Python

What is the fastest way to filter a set of substrings from a string in python?
Use an re: import re shorterstring = re.sub('very, |long ', '', 'some very, very, very, long string') You'll need to make sure that the substrings to replace with nothing are in descending order of length so that longer matches are replaced first. Or, you could avoid the chained calls, and use: reduce(lambda a, b: a.replace(b, ''), ['very, ', 'long '], s)

Categories : Python

a cleaner way to approach try except in python
You could try this, assuming you wrap things in functions: for func in (something, something1, something2): try: func() except Keyerror as e: print e

Categories : Python

How to find multiple substrings of a string, but if multiple are not found, still return however many substrings were found
First, for sake of simplicity, consider those substring variables as an array. Now, the code may look like this, function doIt($string, $sub_strings){ foreach($sub_strings as $substr){ if(strpos($string, $substr) !== FALSE) { return $string; // at least one of the needle strings are substring of heystack, $string } } return ""; // no sub_strings is substring of $string. } and to use this function, echo doIt($string,array($str1,$str2,$str3,$str4)); Thanks to Orangepill!

Categories : PHP

cleaner way to handle python exceptions?
If the cleanup can always run, you can use the finally clause, which runs whether an exception is thrown or not: try: do_something() except: handle_exception() finally: do_cleanup() If the cleanup should only be run in the event of an exception, something like this might work: should_cleanup = True try: do_something() should_cleanup = False except: handle_exception() finally: if should_cleanup(): do_cleanup()

Categories : Python

Cleaner way to iterate through array + create a string from values
For example, package main import ( "bytes" "fmt" ) type User struct { Nick string } func main() { var users [2]User users[0] = User{Nick: "Radar"} users[1] = User{Nick: "NotRadar"} var buf bytes.Buffer buf.WriteByte(':') for _, u := range users { buf.WriteString(u.Nick) buf.WriteByte(' ') } names := buf.String() fmt.Println(names) } This avoids a lot of allocations due to the concatenation of strings. You could also write: package main import ( "fmt" ) type User struct { Nick string } func main() { var users [2]User users[0] = User{Nick: "Radar"} users[1] = User{Nick: "NotRadar"} var buf []byte buf = append(buf, ':') for _, u := range users { buf = append(buf, u.Nick...)

Categories : Go

Break strings into substrings based on delimiters, with empty substrings
Now that we've cleared up what the question is about, here's the issue. Your gmatch pattern will return all of the matching substrings in the given string. However, your gmatch pattern uses "+". That means "one or more", which therefore cannot match an empty string. If it encounters a ^ character, it just skips it. But, if you just tried :gmatch("[^^]*"), which allows empty matches, the problem is that it would effectively turn every ^ character into an empty match. Which is not what you want. What you want is to eat the ^ at the end of a substring. But, if you try :gmatch("([^^])^"), you'll find that it won't return the last string. That's because the last string doesn't end with ^, so it isn't a valid match. The closest you can get with gmatch is this pattern: "([^^]*)^?". This has t

Categories : Lua

Python module organization to make import statement cleaner
Yes. You can import your modules inside of the __init__.py file in the B folder: __init__.py: __all__ = ('B_file_1',) from B_file_1 import B_file_1 Now, your second import statement will work.

Categories : Python

How can search a string to see if it contains all substrings?
You don't need regular expression for this - just use indexOf, check for each words, and return if any of the words was not found var check_string = function(string, words) { var count = 0; for (var i in words) { if (string.indexOf(words[i]) === -1) { return false; } } return true; }

Categories : Javascript

Searching string for different substrings
If your list of substrings is small and the input is small, then using a for loop to do compares is fine. Otherwise the fastest way I know to search a string for a (large) list of substrings is to construct a DAWG of the word list and then iterate through the input string, keeping a list of DAWG traversals and registering the substrings at each successful traverse. Another way is to add all the substrings to a hashtable and then hash every possible substring (up to the length of the longest substring) as you traverse the input string. It's been a while since I've worked in python, my memory of it is that it's slow to implement stuff in. To go the DAWG route, I would probably implement it as a native module and then use it from python (if possible). Otherwise, I'd do some speed checks

Categories : Python

extracting multiple substrings from string using sed
What I would do is to use sed 's/regex to match the old string/new string/' and then write it to a file. so it would be something like this: sed 's/regex to match the old string/new string/' > file and ofcourse to provide sed with input just redirect the standard output of cat: cat thefile.txt | sed ...

Categories : Regex

Removing repeating substrings from within a string in R
One obvious way is to strsplit the string, get unique strings and stitch them together. paste0(unique(strsplit(a, ",[ ]*")[[1]]), collapse=", ")

Categories : Regex

Find all substrings of a string - StringIndexOutOfBoundsException
Analysis of Exception: From Java7 Docs of StringIndexOutOfBoundsException public class StringIndexOutOfBoundsException extends IndexOutOfBoundsException Thrown by String methods to indicate that an index is either negative or greater than the size of the string. From Java 7 Docs of substring public String substring(int beginIndex,int endIndex) Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. I guess this: length of the substring is endIndex-beginIndex comes into String index out of range: -1. I have tested with multiple cases holding my assumption true but appreciate any other proof. For -1: "rum".substri

Categories : Java

Match the string with a regexp to get substrings between '='?
This regex will match explicitly your requirements, and put the non, delimiter portion it the first capture group: =([^=]+)(?==) Unfortunately JavaScript regex does not have look behinds, otherwise this could be done in much easier fashion. Here is some code: var str = '=([^=]+)(?==)'; var re = /=([^=]+)(?==)/g, ary = [], match; while (match = re.exec(str)) { ary.push(match[1]); } console.log(ary);

Categories : Javascript

How to pull out substrings (words) from string?
I see at least two things: You're not computing the indices correctly. The starting index for the third word should be something like length of first word + 1 + length of second word + 1, but it looks like you're leaving out the length of the first word. Similarly, when you're getting the fourth word, you're leaving out the lengths of the first two words. indexOf(" ") will only get you the index of the first occurrence of a space. After you get the first space, you're reusing that index instead of using the indices of the other spaces. Lastly, after you fix those two, if you know that the words are going to be delimited by spaces, then you might want to look at the String.split function. Using that, you could split your sentence without having to do all of the space-finding yourself.

Categories : Java

Python permutations including substrings
import itertools def all_permutations_substrings(a_str): return ( ''.join(item) for length in xrange(1, len(a_str)+1) for item in itertools.permutations(a_str, length)) Note, however, that this is true permutations - as in, hello will have any substring permutation that has two ls in it twice, since the l's will be considered "unique". If you wanted to get rid of that, you could pass it through a set(): all_permutations_no_dupes = set(all_permutations_substrings(a_str))

Categories : Python

get substrings from string with parentheses, brackets and hyphen
If locale, district and town haven't spaces in them: preg_match("/^s*(S+)s*((S+)s*-s*(S+))/", $input_line, $output_array); explanation: The regular expression: (?-imsx:^s*(S+)s*((S+)s*-s*(S+))) matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching ) (matching whitespace and # normally): ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- s* whitespace

Categories : PHP

how to sort substrings separated by blanks in a string
String [] array = temp.split("\s+"); // split by whitespace Arrays.sort(array); // sort using mergesort with insertionsort StringBuilder sb = new StringBuilder(temp.length()); for(String s : array){ sb.append(s).append(" "); } temp = sb.toString(); // assign temp the new string

Categories : Java

Java - using recursion to create all substrings from a string
This problem has overlapping subproblems and because of that the top-down recursion as you do is not much effective. You are evaluating multiple substrings multiple times. Actually it is horribly ineffective (I would guess O(2^n)). Just try to run it on a bit longer string. generate("OverlapingSubproblems"); If you are interested in a better way of solving this you can try something like this: public static void generate2(String word) { for (int from = 0; from < word.length(); from++) { for (int to = from + 1; to <= word.length(); to++) { System.out.println(word.substring(from, to)); } } } If you want to use recursion you can try to rewrite the for-loops with recursion as exercise ;)

Categories : Java

Finding substrings in a string (HTML, Android)
Using an email regex will be a better idea, use pattern Matcher with the following regex(you may correct regex in case any flaws found): ^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)* @[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$; Hope you should be able to code using this info.

Categories : Java

Python match all substrings and reversed strings
You can use regex: >>> import re >>> pat = 'CATA' >>> strs = 'TCATATGCAAATAGCTGCATACCGA' >>> [m.start() for m in re.finditer(pat, strs)] [1, 17]

Categories : Python

How to change order of substrings inside a larger string?
First of all, those options should probably be in a separate table. You're breaking all kinds of normalization rules stuffing those things into a string like that. But if you really want to parse that out in php, split the string into a key=>value array with something like this: $pairs = explode('{', $option_string); foreach($pairs as $pair) { list($key,$value) = explode('}', $pair); $options[$key] = $value; } I think this will give you: $options[3]=15; $options[2]=3; $options[4]=168; $options[5]=52; Another option would be to use some sort of existing serialization (either serialize() or json_encode() in php) instead of rolling your own: $options_string = json_encode($options); // store $options_string in db then // get $options_string from db $options = json_decode($o

Categories : PHP

Python RegEx query missing overlapping substrings
From the Python 3 documentation (emphasis added): $ python3 -c 'import re; help(re.findall)' Help on function findall in module re: findall(pattern, string, flags=0) Return a list of all non-overlapping matches in the string. If one or more capturing groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. If you want overlapping instances, use regex.search() in a loop. You have to compile the regular expression because the API for non-compiled regular expressions doesn't take a parameter to specify the starting position. def findall_overlapping(pattern, string, flags=0): """Find all matches, even ones that overlap.""" regex = re.compile(pa

Categories : Regex

JavaScript - get substrings from complex string (name and units from "some metric [some unit]")
I could do it like this: var parts = source.split('['); var name = parts[0]; var units = parts[1].substring(0, parts[1].length - 1); Demo

Categories : Javascript

Regex for identifying and seperate multiple substrings from a single string
You would need to do this with two seperate passes. Each pass would look for the values you're interested in Pass 1: (?<=s|^)(alan)(_)(d+) Pass 2: (?<=s|^)(roma)(_)(d+) However you wanted to know how to do this without the two pass solution. The best you could use an expression which places each match into a separate capture group, but I think this would be more cumbersome: (?<=s|^)(?=alan|roma)(alan)?(roma)?(_)(d+) Live Demo Sample Text How alan_613 are you roma_222 all doing alan_611 Matches In this example note how capture group 1 gets alan, or capture group 2 gets roma [0][0] = alan_613 [0][1] = alan [0][2] = [0][3] = _ [0][4] = 613 [1][0] = roma_222 [1][1] = [1][2] = roma [1][3] = _ [1][4] = 222 [2][0] = alan_611 [2][1] = alan [2][2] = [2][3] = _ [2][4]

Categories : Java

How do I check existence of a string in a list of strings, including substrings?
If I understood your question then I guess you need any: return any(val in x for x in lst) Demo: >>> lst = ['aaa','dfbbsd','sdfdee'] >>> val = 'bb' >>> any(val in x for x in lst) True >>> val = "foo" >>> any(val in x for x in lst) False >>> val = "fde" >>> any(val in x for x in lst) True

Categories : Python

How to replace some substrings with consequitve numbers in a string using regular expression in java?
You can use appendReplacement and appendTail from Matcher class String data = "some cool color #12eedd more cool colors #4567aa"; StringBuffer sb = new StringBuffer(); Pattern p = Pattern.compile("#[0-9a-f]{3,6}", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(data); int i = 1; while (m.find()) { m.appendReplacement(sb, "#{" + i++ + "}"); } m.appendTail(sb);//in case there is some text left after last match String replaced = sb.toString(); System.out.println(replaced); output: some cool color #{1} more cool colors #{2}

Categories : Java

how to search the database for the keys that are themselves substrings of the search string in mongodb
You can use regex in your search string if it can help: http://docs.mongodb.org/manual/reference/operator/regex/

Categories : Mongodb

matching list of substrings to a list of strings in Python
As described in this answer, a regular expression would be the way to go, since these are modeled as a DFA that can check for all substrings at the same time. You should probably read that answer, as it is quite in-depth.

Categories : Python

Find num of overlapping and non-overlapping substrings in a string
I have a (Java) solution that performs O(N) or O(N**3), for a resulting 90/100 overall, but I can't figure out how to make it go though 2 different testcases: almost_all_same_letters aaaaa...aa??aaaa??....aaaaaaa 2.150 s. TIMEOUT ERROR running time: >2.15 sec., time limit: 1.20 sec. same_letters_on_both_ends 2.120 s. TIMEOUT ERROR running time: >2.12 sec., time limit: 1.24 sec. Edit: Nailed it! Now I have a solution that perform in O(N) and passes all the checks for a 100/100 result :) I didn't know Codility, but it's a nice tool!

Categories : Python

Is there a cleaner way to set this up?
I know nothing about the bootstrap-datepicker, but i am sure you would have to write a basic integration like this and base your Datepicker upon it. I have done something similar using jQuery UI instead of Bootstrap. // generic logic so that options and event handlers can be declared nicely App.GenericDatePickerView = Ember.View.extend({ didInsertElement: function() { var options = this._gatherOptions(); var datepicker = this.$().datepicker(options); this.get("uiEvents").forEach(function(uiEvent){ datePicker.on(uiEvent, function(){ var fn = that.get(uiEvent); fn.call(that); }); }); this.set("datepicker", datepicker); }, _gatherOptions: function() { var uiOptions = this.get('uiOptions'), options = {}; uiOptions.forEach(function

Categories : Ember Js

file cleaner using regex
re.findall('(?m)<.*?>',s) -- or -- re.findall('(?m)<[^>]*>',s) The question mark after the * causes it to be a non-greedy match, meaning that it only takes as much as it needs, as opposed to normal, where it takes as much as possible. The second form is used more often, and it uses a character class to match everything but <, since that will never exist anywhere inside the tag excepting the end.

Categories : Python

Trying to create cleaner sql syntax
To Check if all Columns are not null: select * from table where completedDate is not null and completedBy is not null and cancelDate is not null and cancelBy is not null

Categories : SQL

Using DataBase Cleaner gem with DataMapper
First make sure you have dm-transactions in your Gemfile as well as database_cleaner and require both in your spec helper: require 'dm-transactions' require 'database_cleaner' Then you just need to configure DatabaseCleaner to use DataMapper with the following line in your spec helper: DatabaseCleaner[:data_mapper].strategy = :transaction You can now use something similar to this in your specs to let DatabaseCleaner know when the transactions start and when to clean: before :each do DatabaseCleaner.start end after :each do DatabaseCleaner.clean end More details on DatabaseCleaner readme: https://github.com/bmabey/database_cleaner

Categories : Ruby On Rails

Filter Data In a Cleaner/More Efficient Way
Use logical indexing: rows = (big(:, 1) == 3 | big(:, 1) == 6); big(rows, :) = []; In the general case, where the values of the first column are stored in filterRows, you can generate the logical vector rows with ismember: rows = ismember(big(:, 1), filterRows); or with bsxfun: rows = any(bsxfun(@eq, big(:, 1), filterRows(:).'), 2);

Categories : Performance

Konesans Regex Cleaner Transformation
So I've never used Konesans Regex Cleaner and I don't particularly want to download it, but as per your comment I'll try to help. Looking at their samples online, it looks like all you have to do is put [!@#$%^&*_+`{};':,./<>?] in the "Match" column, and nothing at all in the replace column. Perhaps an empty string - "" You can use this to test your find and replace regexes. Here are a few examples so you can get a feel for it: String: This #is &&%^an !ugly &$%^string. Match: [!@#$%^&*_+`{};':,./<>?] Replace: Result: This is an ugly string Match: [!@#$%^&*_+`{};':,./<>?] Replace: - Result: This -is ----an -ugly ----string- Match: [!@#$%^&*_+`{};':,./<>?]+ Replace: - Result: This -is -an -ugly -string- Edit: since you can't

Categories : Regex

How refactor switch in javascript for cleaner code?
After looking at all your conditions, it seems to boil down to this: function filterForm(purpose, entry) { var q1 = purpose == 'Business' || entry == 'Single' ? 'block' : 'none'; var q2 = purpose == 'Business' && entry == 'Multiple' ? 'block' : 'none'; var q3 = purpose == 'Tourist' && entry == 'Single' ? 'block' : 'none'; $("#moreq1").css( "display", q1 ); $("#moreq2").css( "display", q2 ); $("#moreq3").css( "display", q3 ); }

Categories : Javascript

HTML Cleaner + XPath Not Working in Android App
Problem was that the http request was being redirected to the mobile website. This was solved by changing the User-Agent property like so. private static final String USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0"; HttpURLConnection lConn = (HttpURLConnection) argv[0].openConnection(); lConn.setRequestProperty("User-Agent", USER_AGENT); lConn.connect(); lNode = cleaner.clean( lConn.getInputStream() );

Categories : Java

jQuery Newbie, is there a cleaner way to write this code?
Use css to hide and show since its on document ready you dont need to use jQuery to hide it .mobile-search, .mobile-top-links, .mobile-checkout { display: none; } .cart_show, .account_show, .search_show { display: block; }

Categories : Jquery

PHP - Avoiding nested if statements - cleaner way to code this
You don't need the empty checks at that point, move them to the validation functions. For example: function validate_email($str) { if(empty($str)) { return false; } $str = trim(strtolower($str)); if(!filter_var($str, FILTER_VALIDATE_EMAIL)) { return false; } else { return $str; } } $email = validate_email($_POST['email']); if($email) { // your code }

Categories : PHP



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