w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Remove querystring parameters from url with regex
If you're doing this in-browser, let the browser do the parsing: location.origin + location.pathname Or for arbitrary URLs: function withoutQS(_url) { var url = document.createElement('a'); url.href = _url; return url.origin + url.pathname; }

Categories : Javascript

Parsing SQL statements with regex: Does adding the optional flag in a regex expression change how greedy or posessive modifiers are matched?
Parsing SQL with regex is not much different from parsing HTML with regex. In other words, it won't work. It is hopeless task, stop right now. Instead, use some SQL parser. For example, SQL::Statement::Structure for Perl or ANTLR for Java. Also, since you are creating your own database, it is worth taking a look at how other SQL implementations do it. I would recommend reading source code for PostgreSQL or MySQL and see how they implement advanced SQL parsing.

Categories : Java

Javascript / REGEX: Delete a specific Text (word) starting with a specific letter inside a String with words separated by spaces
How about: str.replace(/sS+/ig,"") Explanation: NODE EXPLANATION ----------------------------------------------------------------------  the boundary between a word char (w) and something that is not a word char ---------------------------------------------------------------------- s 's' ---------------------------------------------------------------------- S+ non-whitespace (all but , , , f, and " ") (1 or more times (matching the most amount possible)) ---------------------------------------------------------------------- i is for case-insensitive g is for global

Categories : Javascript

Redirect olddomain querystring layout to newdomain and new querystring layout?
First condition match the domain, second condition match the query string and the rule will match your domain root: RewriteCond %{HTTP_HOST} ^old.myurl.org$ [NC] RewriteCond %{QUERY_STRING} ^oldvar=(w+)$ RewriteRule ^$ http://new.myurl.org/?newvar=%1 [R=301,L] You can place more than one query string as well: RewriteCond %{HTTP_HOST} ^old.myurl.org$ [NC] RewriteCond %{QUERY_STRING} ^oldvar=(w+)$ [OR] RewriteCond %{QUERY_STRING} ^oldvar=(w+)&oldvar2=(w+)$ RewriteRule ^$ http://new.myurl.org/?newvar=%1&newvar2=%2 [R=301,L] RewriteCond %{HTTP_HOST} ^old.myurl.org$ [NC] RewriteCond %{QUERY_STRING} ^oldvar2=(w+)$ RewriteRule ^$ http://new.myurl.org/?newvar2=%1 [R=301,L] To use a path like x/y/z as you have mentioned on the comment you change the RewriteRule for example the rule w

Categories : Htaccess

Regex to carry out parsing
class sql { public static void main (String [] args) { String dateInCase = "11/11/2010"; String termID; String line = " 111110 12:24 10390011"; String[] parts = line.split(""); String termId = parts[4]+parts[5]+parts[6]; //to catch terminal ID String cardInserted = parts[1]+parts[2]+parts[3]+parts[4]+parts[5]; String starter = parts[4]+parts[7]+parts[13]+parts[14]+parts[15]; String tracker = parts[3]+parts[4]+parts[5]+parts[6]+parts[7]; boolean V = (termId.matches("\s\d\d")); boolean W = (cardInserted.matches("\s\s\s\s\s"));//this gets card inserted boolean X = (starter.matches("\D\d\d\d\d"));// a new event set has started boolean Y = (tracker.matches("\d\d\d\D\s")); //

Categories : Java

Parsing a string in C# using Regex
Assuming that's always the format of the string you'd be parsing, you could just use a simple String.Split: var elements = yourString.Split(new[] {'(', ')', '|', ',', ' '}, StringSplitOptions.RemoveEmptyEntries); Then just use elements[0] to get the value represented by A, etc. and cast it back to an integer or whatever you need to do with it.

Categories : C#

Parsing CSS files using RegEX
Please do not reinvent the wheel, where you can avoid... There are a multitude of CSS parsers that are freely available on the internet. If you are keen to know how it is done, crack open one of the open source ones and see how it is done. Here's an example that took 2 minutes to find: https://github.com/sabberworm/PHP-CSS-Parser#value I have pointed you to the part that actually shows how to extract the URL too.

Categories : PHP

Parsing iOS 6 emoji with regex
The Java regular expression engine behaves like a good Unicode regular expression engine should in that it matches Unicode codepoints, not UTF-16 chars. You appear to be writing your pattern expecting the latter behavior. Don't do this - instead, when specifying astral-plane characters in a Java regex, use hexadecimal notation for the full codepoint value. For example, to match CLAPPING HANDS SIGN, use x{1f44f}. So your last regex (which would match the BMP Private Use Area, the Miscellaneous Symbols and Pictographs block, the Emoticons block, the Transport and Map Symbols block, the Alchemical Symbols block, and a fair bit of unallocated space in the SMP besides - are you sure you need to match all of those?) should be rendered as: "[ue000-uf8ff]|[\x{1f300}-\x{1f7ff}]"

Categories : Android

Regex parsing of ASP.NET tags
I'd try matching the list of attributes, assuming an attribute is wrapped in quotes or single quotes. This is an assumption that isn't correct for all HTML, but it may work for you: <mw:Translate #opening <mw:Translate> tag # Match attributes (?:s+w+(?:s*=s*(?:"[^"]*"|'[^']*'))?)* s* > #match > s* (?<text>.*?) #capturing group for the localizable text s* #match any whitespace </mw:Translate> #match closing tag Working example: http://regexhero.net/tester/?id=5834b4f1-095b-4af6-a0da-d1fe119778bc

Categories : C#

Parsing a perl regex
It's all as you say. ,"", matches a comma followed by two double-quotes followed by a comma. Commas aren't significant in regex patterns. ^ is an anchor (start of string). It only negates when the first character of a character class ([^...]). A better approach would be to parse the line into fields using Text::CSV_XS, then match against the values obtained. if ( my ($num) = $row->[0] =~ /^(d+)_[^,]+z/ and $row->[1] eq "" and ... ) { ... } elsif (... ) { ... }

Categories : Perl

Redirecting one URL with querystring to another URL with querystring
In General you dont need to specify anything to append the querystring. Following should work Keep original query (default behavior) RewriteRule ^page.php$ /target.php [L] # from http://example.com/page.php?foo=bar # to http://example.com/target.php?foo=bar

Categories : Htaccess

regex validation not parsing string in if PHP
You made the entire capturing group optional: ^([A-Z][0-9][A-Z][0-9][A-Z][0-9])?$^ ^ It's also not a good idea to use regex metadata characters as your delimiter. Try this regex, which matches an uppercase letter and a number three times: /^((?:[A-Z][0-9]){3})$/ You don't need to make the capturing group optional because you handle the logic for when the user doesn't submit a code with the && $_POST['txtPostalCode'] != "" part of the if statement. Finally, since you're not even using the matches from this regex, you don't need the capturing group: /^(?:[A-Z][0-9]){3}$/

Categories : PHP

Javascript Dynamic Regex Parsing
You've put a regex literal syntax inside a string. You should either use the regex literal syntax: var regex = /cat|bat|dog/i; Or pass a string (without delimiters/modifiers) as the first argument to the RegExp constructor: var regex = new RegExp('cat|bat|dog', 'i'); Also you'll need the g flag (global modifier) to test the regular expression against all possible matches, otherwise only the first match will be returned. Complete example: var regex = /cat|bat|dog/ig; //or new RegExp('cat|bat|dog', 'ig'); var string = "A dog saw a cat and a bat"; var matches = string.match(regex); matches; //["dog", "cat", "bat"]

Categories : Javascript

Parsing SEC RSS Title field using regex
If the company name does not contain the string " - ", the SIC Number is only numbers and there is a space before the opening bracket, this is what you are looking for: m = re.search(r' - ([^(]+?) ((d+))',t)

Categories : Python

Parsing big text file using regex
You can use islice. from itertools import islice file = open('file.txt', 'r') while True: slice = islice(file, buffer) to_process = [] for line in slice: to_process.append(line) if not to_process: break #process to_process list file.close() buffer is the number of lines you want to read at a time (you have to define the int).

Categories : Python

Parsing text in a file with regex
You read the file already. The file pointer is now at the end and you won't read any more data. Store the file data once: contents = f.read() print contents # prints '22 test 333' print data.findall(contents) # outputs ['22'] Alternatively, seek back to the start: print f.read() # prints '22 test 333' f.seek(0) print data.findall(f.read()) # outputs ['22'] or reopen the file.

Categories : Python

Parsing links with Perl regex
use 5.014; for my $link ($mech->find_all_links(url_abs_regex => qr/d+xd+.html$/a)) { my ($w, $h) = $link->url =~ /(d+)x(d+)/a; if ($w <= 1440 && $h <= 900) { # do something } }

Categories : Regex

RegEx Address Parsing City
Personally, I think I would take a totally different approach. I would treat the zip code as authoritative, as it is the most granular data you have available. I would get a list of zip code to city mappings. Extract the zip code portion of the address. Write in new database fields the city and state values based on the zip code. Then write a script to go through each data entry and determine if the city and state names based on zip code can be found in your string. If they can, remove those values from the string. And flag that record as successfully processed. If they can't flag the record as one that you might need to perform manual review on. Another alternate approach might be to use an API like Google Maps, to send your address string to and hopefully get a cleaned address out

Categories : Regex

Regex For Parsing Object Literal
Seems that what you need is 'non-greedy' matches (*? instead of *) - it captures the shortest match rather than the longest. So the regex will look like: /^(stores[)(d){1,2}(])(.| )*?};$/m After suggesting that I still have to note that you in general should not do that with regular expressions at all :). Your approach will break if the object string properties contain '}' (e.g., 'fullName' : 'Bobs Comm}ons').

Categories : Javascript

Regex for parsing string with same type of expression
You can use lookarounds which perform only a check but don't match: lookahead (?=...) lookbehind(?<=...) example: (?<=\"6\":\")[^"]++(?=") An another way is to use a capturing group (...): \"6\":\"([^"]++)" Then you can extract only the content of the group. Example: Pattern p = Pattern.compile("\"6\":\"([^"]++)""); Matcher m = p.matcher(yourString); if (m.matches()) { System.out.println(m.group(1)); }

Categories : Java

Parsing non-node, intermittent XML values using regex
Description This regex will capture the first level of text (?:[s ]*<([^>s]+)s?(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^s>]*)*>.*?</1>)?[s ]*K(?!)(?:(?![s ]*(?:<|)).)*1 Expanded (?:[s ]*<([^>s]+)s?(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^s>]*)*>.*?</1>)? # match any open tags until the close tags if they exist [s ]* # match any leading spaces or new line characters K # reset the capture and only capture the desired substring which follows (?!) # validate substring is not the end of the string, this prevents the phantom empty array value at the end (?:(?![s ]*(?:<|)).)* # capture the text inside the current substring, this expression is self limiting and will stop when it sees whitespace ahead followed by end of st

Categories : PHP

Parsing plain text with AWK regex tools
Code for GNU awk BEGIN { FS = "[ .,]"} { for (i = 1; i <= NF; i++) { if ($i ~ /[0-9]/){ print($i, $(++i)) } } } $awk -f a.awk file 20 m 1/2 kg 5 kg 10 m/s2

Categories : Regex

Java string parsing with different regex to split
I don't think a regex will help you here, whoever designed that output String clearly didn't have splitting in mind. I suggest simply parsing through the String with a loop and doing the whole thing manually. Alternatively you can just look through the String for substrings (suck as "Tick for symbol"), then take whatever word comes after (until the next space), since the second parameter always seems to be one words.

Categories : Java

stack overflow error with regex for parsing
SIN((d+.?d*)) Edit live on Debuggex I edited to allow for numbers with decimals. Instead of random . and digits. (?:SIN|COS|TAN)(([-]?d+.?d*^?d*)) Edit live on Debuggex this allows for the functions sin, cos, or tan to be used to add more functions just add a |{functionname} at the start. Also, it can be a negative value with an exponent. or you can have .+(([-]?d+.?d*^?d*)) Edit live on Debuggex This will allow for anything to be in front of the () I don't quite understand what you want with the * - /what i suggested is that you make separate REGEX for each function so you can handle them differently.

Categories : Java

How to grab this data from this URL without using regex or parsing the string?
In PHP, you can get this with the PATH_INFO server variable. This provides any client-provided pathname information trailing the actual script filename but preceding the query string (source) In this case, $_SERVER['PATH_INFO'] will be /myvalue.

Categories : PHP

best way to parsing Large files by regex python
"The best way to do the above task in minimal time" is to first figure out where the time is going. Look into how to profile your Python script to find what parts are slow. You may have an inefficient regex. Writing to sqlite may be the problem. But there are no magic bullets - in general, processing 2GB of text line by line, with a regex, in Python, is probably going to run in minutes, not seconds. Here is a test script that will show how long it takes to read a file, line by line, and do nothing else: from datetime import datetime start = datetime.now() for line in open("big_honkin_file.dat"): pass end = datetime.now() print (end-start)

Categories : Python

Java regex for parsing Qt localization functions params
Actually it's possible to reach content between quotes and then seeking for ). Pattern will look like Pattern.compile("\qsTr?\s*\(\s*(((".*?(?<!\\)")|('.*?(?<!\\)')).*?)(?=\))", Pattern.DOTALL); It guarantees if content wrapped by qsTr() starts from " it will definetely be extracted. For example if you to parse next string: qsTr("source", count) you'll get next result: "source", count And then you can check for validity of extracted string (for example, if it is possible for qsTr function to contain another params after static string param).

Categories : Java

Parsing text by regex, split, tokinize, or hash
This is pretty straightforward to match with regex if you know that there is at least one of those present in the string. For example: (?:(d+)s*hours?)?s*(?:(d+)s*minutes?)?

Categories : Ruby

python regex parsing xml, save the results to the dictionary. Like the following
You can use BeautifulSoup: >>> from bs4 import BeautifulSoup as BS >>> xml = """<manifest> ... <item href="Text/Briefcontent.xhtml" id="Briefcontent.xhtml" media-type="application/xhtml+xml" /> ... <item href="Text/Section115.xhtml" id="Section115.xhtml" media-type="application/xhtml+xml" /> ... </manifest>""" >>> soup = BS(xml, 'xml') >>> d = {} >>> for i in soup.findAll('item'): ... idict = i.attrs ... d[idict['id']] = idict['href'] >>> d {u'Briefcontent.xhtml': u'Text/Briefcontent.xhtml', u'Section115.xhtml': u'Text/Section115.xhtml'}

Categories : Python

Posix RegEx for parsing email message - how to stop after first occurrence of boundary
POSIX doesn't have greediness modifiers, there's a way to do it but it's ugly and long. To simplify, say the token was much shorter, like --123, you'd need this regex: ^(([^-]|-[^-]|--[^1]|--1[^2]|--12[^3])+) That's already insanely long for something so simple. Basically you're telling the regex that you want a repetition of anything that isn't -, or a - followed by anything that isn't -, or -- followed by anything that isn't 1, and so on and so on. I made a script to produce a regex from an input token and ran it with --------------010402010107070509040804 and it gave me this: ^(([^-]|-[^-]|--[^-]|---[^-]|----[^-]|-----[^-]|------[^-]|-------[^-]|--------[^-]|---------[^-]|----------[^-]|-----------[^-]|------------[^-]|-------------[^-]|--------------[^0]|--------------0[^1]|------

Categories : Regex

Javascript regex or other parsing technique to extract the contents of last set of parentheses in a string
Assuming they are not nested you can simply do: /(([^)]+))$/ var foo = "Some title (8888)(123, bar)(1000, foo)"; // Get your result with foo.match(/(([^)]+))$/)[1]; Demonstration: http://regex101.com/r/tS2yS1

Categories : Javascript

Parsing specific part of XML file
Since you never declare the namespace (xmlns:gpxtpx="http://www.topografix.com/GPX/1/1") it is never going to match. The xml fragment you provided is not well formed due to the lack of the namespace. If the fragment posted is snipped from a larger document, consider switching to XML API's rather than string manipulation. If that is the entirety of the XML you receive from an outside system, add it to a root node which you can declare the schema in: <root xmlns:gpxtpx="http://www.topografix.com/GPX/1/1"> <!-- put your xml fragment here --> </root>

Categories : C#

NSString parsing for specific values
Use an NSDicationary. NSDictionaries are key value stores. In other words, there are a list of keys. Each key is unique. Each key has an associated value. The value can be any data type and the key has to conform to the NSCopying protocol (typically an NSString). If you try to access the value for a key that doesn't exist in your NSDictionary, the return value will be nil. //create the dictionary and populate it NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; [dict setObject:@"value_1" forKey:@"key_1"]; [dict setObject:@"value_2" forKey:@"key_2"]; [dict setObject:@"value_3" forKey:@"key_3"]; [dict setObject:@"value_4" forKey:@"key_4"]; NSString *stringInput = [self getStringInput];//however you find out your input //find your string value based on the key passed i

Categories : Objective C

Bash / Regex Parsing only Domain Names In File containing both Domans and Email Addresses
if your file contains only domain and email addr, try this line: grep -v '@' file test with your example: kent$ echo "john3525@aol.com brenda392@yahoo.com xyx.net boxers.on.ca helloworlds.co.uk"|grep -v '@' xyx.net boxers.on.ca helloworlds.co.uk

Categories : Regex

parsing xml tags in a specific order in python
Sort the test sets by their order attribute: root = tree.getroot() testsets = root.findall('testset') for testset in sorted(testsets, key=lambda ts: int(ts.attrib['order'])): # test sets are looped over in the order specified in the `order` attributes testcases = testset.findall('testcase') for testcase in sorted(testcases, key=lambda ts: int(ts.attrib['order'])): # test cases are looped over in the order specified

Categories : Python

Json parsing error for specific string
The string needs to look like this: {"Path":"5984fcb4-8bf8-4205-86f8-e6e2042ba610.jpg","StatusCode":"OK"} You might also need single quotes around that: '{"Path":"5984fcb4-8bf8-4205-86f8-e6e2042ba610.jpg","StatusCode":"OK"}'

Categories : Jquery

Parsing this specific JSON from a auto directed url in Android
The answer to your problem is stated in your stack trace : Your content must have a ListView whose id attribute is 'android.R.id.list' The corresponding activity seems to be your AndroidJSONParsingActivity which extends ListActivity. A ListActivity performs many things automatically and assume that your layout (in your case R.layout.main) contains a ListView with the android.R.id.list. Check your main layout and make sure that you have a ListView like this : <ListView android:id="@android:id/list" [...] />

Categories : Android

Trouble with parsing a .txt file for specific strings in Python
Looks like you could use a regex instead: s = 'CRIT : [2013-07-26T14:40:50-0400] msg=<POLICY ADDED>,' import re print re.match(r'(w+).*?msg=<(.*?)>', s).groups() # ('CRIT', 'POLICY ADDED')

Categories : Python

Pulling data from a webpage, parsing it for specific pieces, and displaying it
This small example uses HtmlAgilityPack, and using XPath selectors to get to the desired elements. protected void Page_Load(object sender, EventArgs e) { string Url = "http://www.metacritic.com/game/pc/halo-spartan-assault"; HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load(Url); string metascore = doc.DocumentNode.SelectNodes("//*[@id="main"]/div[3]/div/div[2]/div[1]/div[1]/div/div/div[2]/a/span[1]")[0].InnerText; string userscore = doc.DocumentNode.SelectNodes("//*[@id="main"]/div[3]/div/div[2]/div[1]/div[2]/div[1]/div/div[2]/a/span[1]")[0].InnerText; string summary = doc.DocumentNode.SelectNodes("//*[@id="main"]/div[3]/div/div[2]/div[2]/div[1]/ul/li/span[2]/span/span[1]")[0].InnerText; } An easy way to obtain the XPath for a given element is by using y

Categories : C#

Error: taglib definition is not consistent with specific version during parsing web.xml
Your web.xml elements are defined according to pre 2.5 servlet spec. Because you are using 2.5 or post 2.5(3.0) servlet spec, do as below: <jsp-config> <taglib> <taglib-uri>mytags</taglib-uri> <taglib-location>/WEB-INF/MyTags.tld</taglib-location> </taglib> <jsp-config>

Categories : Java



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