w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to create hyperlink after finding the words from text file
Not sure why you don't just use explode to split up the pieces of each line in the input file, unless the format of the input is different from what you showed. Otherwise you can use file() to read in the input file, which returns an array of lines in the file. Then you can loop through this array and explode every line into two pieces. The first piece is the name, the second the hyperlink. Then just create the link tag and you're all set. Example code: <?php $lines = file('input.txt'); foreach ($lines as $curLine) { $pieces = explode(" ", $curLine, 2); echo sprintf("<a href="%s">%s</a> ", trim($pieces[1]), trim($pieces[0])); } Edit: Just saw your update and noticed you have multiple spaces or other whitespace characters between the tokens on each line. In tha

Categories : PHP

Regexp grab all text following last match
This is the regex you will need: /^.*?(d+(?=D*$)s*)/ And just replace matched text with empty string "" PHP code: $s = preg_replace('/^.*?(d+(?=D*$)s*)/', '', 'Foo Oz'); //=> Foo Oz $s = preg_replace('/^.*?(d+(?=D*$)s*)/', '', '1/2 Oz'); //=> Oz Live Demo: http://ideone.com/u887D7

Categories : PHP

text file doesn't match when i try to create text box according to the text file
It's creating 10 more because you have 10 lines that ends with a comma. Say you have a string like: var s = "A,B,C," Splitting this would result in 4 string, the last one being empty. Now reproduce this for 10 lines and you will get the same behaviour as you are having. If that's unwanted behaviour, you need to change your logic to take into account a line that is ending with a comma.

Categories : C#

regexp to match text between . " and blank line
You can use . ".* this will give you . "question title 1" as one of the match. You can read from fourth char to last but one. I couldn't figure out a way to match both question and answer line using regular expression. Because, this regular expression will match multiple lines but . "[sS]+ but it will match until end of the string matching all questions and answers into a single string. If we assume that the answers will always start with either + or *, Another alternative is to use (. ".*)|([*+].*) This will match both questions and answers. However questions and answers will be separate matches. Another way is to split the string using id. " This will give each of your question and answer into another string. However you may have to remove the " at the end of the question manually.

Categories : Javascript

Match consecutive lines in a file.
Description You'll have to modify the "what I'm searching for" block to contain all the same leading spaces as exist in the target data. Your search for text will need to be inserted into this expression between the Q...E tags. The expression will then find the template name for the block of text you've selected, the name will be placed into Capture Group 1. ^template:s*(S*).*?(?=^)(?:^s+(?:(?!^).)*)*?^Q - type: cfgstore hosts: - {name: ymscfg-02.ops.bf1.yahoo.com, farm: east} - {name: ymscfg-02.ops.gq1.yahoo.com, farm: west} - type: aggregator hosts: - {name: ymsagg-08.ops.bf1.yahoo.com, farm: east} - {name: ymsagg-10.ops.gq1.yahoo.com, farm: west} - type: metricsdb hosts: - {name: ymsdb-11.ops.bf1.yahoo.com, farm: east} - {name: ym

Categories : Regex

A program that opens a text file, counts the number of words and reports the top N words ordered by the number of times they appear in the file?
Use collections.Counter for counting words and open() for opening the file: from collections import Counter def main(): #use open() for opening file. #Always use `with` statement as it'll automatically close the file for you. with open(r'C:Data est.txt') as f: #create a list of all words fetched from the file using a list comprehension words = [word for line in f for word in line.split()] print "The total word count is:", len(words) #now use collections.Counter c = Counter(words) for word, count in c.most_common(): print word, count main() collections.Counter example: >>> from collections import Counter >>> c = Counter('aaaaabbbdddeeegggg') Counter.most_common returns words in sorted order based

Categories : Python

MySQL/Regexp: Partial regexp match
This should do it on MySql: select * from table t where 'foo-11.example.com' rlike t.data; There are other ways in PostGreSQL. Here's the link from where I have referenced this: http://www.tutorialspoint.com/mysql/mysql-regexps.htm Match a Query to a Regular Expression in SQL? PS: Using * is tricky though!

Categories : Mysql

Extracting both the full match, and the last token match in a regexp
I guess you could use this regex: =hyperlink("([@\ws()-./]+\([^"]+))") And this new replace: <a href="file:///$1">$2</a> I'm not sure how your regex was working, but I added the quotes in the regex and replaced the single quotes by double quotes in the replace. Revert those if need be. Demo

Categories : Javascript

how to find words that has 2 consecutive same characters using egrep?
Use a back-reference: egrep '(w)1' file will match any two consecutive "word characters". The (w) creates a "group" that matches any word character. The 1 refers to whatever was matched in the first group (which here means the previous character. $ cat test abcdefg 1234567 abcddefgj 88427 $ egrep '(w)1' test abcddefgj 88427

Categories : Unix

Regex that selects everything after first consecutive capitalized words
The following expression with match all consecutive capitalized words at the beginning of the sentence. ^(?:(?:[A-Z][a-z]+)(?>s*))+ Regex101 Demo If you want to remove that part from the setnence then all you have to do is replace it with the empty string. If you want to replace the part that comes after it then you can use the following expression: ^((?:(?:[A-Z][a-z]+)(?>s*))+)([sS]+) and use a replacement string of $1 or whatever in your language that is used to reference the first captured group. Regex101 Demo

Categories : Regex

How create a single Prolog rule that match with more then a single words list?
by far the easiest way will be to declare both alternative, and let Prolog match the appropriate one. This could result in maintenance problems in long term, then could be worth to evaluate how many of such patterns you are willing to support, and eventually factor out the common code. The most important detail is that your rules should be side effect free - as it seems at first glance.

Categories : Prolog

Parsing a string into parts, only consecutive words, not a power set
First of all, I just want to let you know that if you are going to run ALL these against an SQL database for a search, it's extremely inefficient, and suggest you use the LIKE option. http://www.techonthenet.com/sql/like.php Now, to get all the possible combinations, just break up the words into an array (like you've done with explode), and follow the advice given by @ulvund on this question: PHP: How to get all possible combinations of 1D array? Which is to say <?php $array = explode(" ", "listing of average salaries in germany for 2011"); function depth_picker($arr, $temp_string, &$collect) { if ($temp_string != "") $collect []= $temp_string; for ($i=0; $i<sizeof($arr);$i++) { $arrcopy = $arr; $elem = array_splice($arrcopy, $i, 1); // remo

Categories : PHP

Regexp change words that arent between " "
This regex should work for you: hero(?=(?:(?:[^"]*"){2})*[^"]*$) Explanation: Which basically means match a literal text (hero) if it is followed by even number of double quotes in other words match a desired text if it is outside double quotes. Testing: String str = "hero "dont-hero""; String repl = str.replaceAll("hero(?=(?:(?:[^"]*"){2})*[^"]*$)", "FOO"); //repl = FOO "dont-hero" Live Demo: http://ideone.com/BXJxpw

Categories : Java

Regexp for whole words, punctuation included
You should be able to use word boundaries. Otherwise you'll have to declare all of the characters that you're willing to accept. select id,myRecord from my_records where myRecord REGEXP '[[:<:]]lion[[:>:]]'; Here's an SQL Fiddle using some of the examples that you've provided for matching. Note that because the . character in Lion.tiger is typically considered a word barrier (end of sentence declaration) in English, you might need to make a special case where you're not matching it. select id,myRecord from my_records where myRecord REGEXP '[[:<:]]lion[[:>:]]' and myRecord NOT REGEXP '[[:<:]]lion.[[:alpha:]]'; Example fiddle.

Categories : Mysql

Emacs Evil mode: how to create a new text object to select words with any non-space characters?
The correct regexp is " |.?$". The following code implements a new text object matching any nonspace character. (evil-define-text-object evil-inner-space (count &optional beg end type) "Select inner space." :extend-selection nil (evil-regexp-range count beg end type "[ ]" " \|.?$" t))

Categories : Emacs

How connect words in a text file
awk -F":" '{a[NR]=$0} /^ B:/{print line;line=$2} /^ I:/{line=line" "$2} END{ if(a[NR]!~/^B/) {print line} }' Your_file

Categories : Unix

php regexp last match
You can use regex pattern with negative lookahead (?!…) </p>(?!.*</p>) Example: http://www.debuggex.com/r/rgV-ddCbL-BH_rL_/0

Categories : PHP

How do I change the text interpreter in sprintf
sprintf has no interpreter, as it has nothing to do with the display. The bit you need to look at is waitbar. An alternative to changing the interpreter would be to replace any instances of _ with \_ - that is, use the escape character. This could be done like so: waitbar(k/K,h,strrep(sprintf('Processing %s (%u/%u)',filename,k,K), '_', '\_'));

Categories : Matlab

Search for string in text file in-between two key words
You can save ArtistName and SongName as keys in a dictionary using regular expressions if you want. Here are some links to explanations of regular expressions: Python Docs and Tutorials Point import re s = #string you're parsing regex = re.compile(r'w+ = ".*";') matches = regex.findall(s) dict1 = {} for m in matches: elems = m.split(" = ") dict1[str(elems[0])] = elems[len(elems) - 1].strip(';') print (dict1['ArtistName']) print (dict1['SongName']) Output (using your example string): '"FUN."' '"We Are Young"'

Categories : Python

How to print words ending in "rry" from a text file?
grep rry$ sample.txt Sample.txt: 1 carry 2 car 3 house 4 notebook 5 handbook 6 party 7 hurry 8 rryasdf Prints carry hurry

Categories : Regex

Regexp, greediness until second match
If there are no nesting, you can use this regex: ^(.*?)s*(?:[([^]]*)])?$ regex101 demo Otherwise, if you can have nested [] in the main [], then the regex will have to be revised. You can make a regex for nested [] but only up to a certain level of nesting; if you have up to 2 levels of nesting, you make a regex for 2, if you have up to 5 levels of nesting, you make a more complex one for 5, etc.

Categories : Javascript

Regexp: match and exclude
I tested this with your single lines from the list ^image(?!.*_small.*).*.png$ see also this discussion on how to exclude keywords in regex

Categories : Regex

Regexp to match ads and not downloads
DEMO regex101 Regex (?:.?)ad(?:.?) Description  Word boundary: match in between (^w|w$|Ww|wW) (?:.?) Non-capturing Group . 0 to 1 times [greedy] Any character (except newline) ad Literal ad (?:.?) Non-capturing Group . 0 to 1 times [greedy] Any character (except newline)  Word boundary: match in between (^w|w$|Ww|wW) Visualization (Provided by debuggex)

Categories : Regex

Match a string with regexp
Well, I'll assume your delimiter is at least two - long and is seperated via a space from the contents. Then a trivial regex like --s+(.*?)s+-- would already work. The *? quantifier does non-greedy matching, to terminate as early as possible. If this regex works depends strongly on allowed values and the exact format of your input, which you have not sufficiently explained. I am also suprised you tagged this as Perl — I am quite sure your code isn't valid Perl code. If you do not want to use the . character class, then we can rewrite it to match all non-hyphen characters or a single hyphen followed by a non-hyphen: --s+((?:[^-]+|-[^-])*)s+-- You might want to disallows newlines along the hyphens as well.

Categories : Regex

Read from a text file and parse lines into words in C
It appears that you are separating words by spaces, so I think just while ((c =fgetc(input_file)) != EOF ) { if (isalpha(c)) { c = tolower(c); putchar(c); } else if (isspace(c)) { putchar(' '); } } will work too. Provided your input text won't have more than one space between words.

Categories : C

Turning a text file with words and their positions into a sentence
Read the file, appending the word and positions as tuples to a list. Then sort that list, remove the indices and join the words: with open(inputfilename) as inputfile: words = [] for line in inputfile: line = line.strip() if not line or line.startswith('#'): continue word, positions = line.split(':') words.extend((int(p), word) for p in positions.split(',')) print ' '.join([w for p, w in sorted(words)]) Demo: >>> with open(inputfilename) as inputfile: ... words = [] ... for line in inputfile: ... line = line.strip() ... if not line or line.startswith('#'): ... continue ... word, positions = line.split(':') ... words.extend((int(p), word) for p in positions.split(',')) ...

Categories : Python

perl regexp with sas - exact match one or the other
Description This regex will match the numbers in the string providing the numbers are surrounded by whitespace or the symbols. (?<=s|^)(?:[0-9]+|one|two|three|four|five|six|seven|eight|nine|ten)(?=s|$) Live Example: http://www.rubular.com/r/6ua7fTb8IS To include the spelled out word version of numbers outside of one - ten, you'll need to include those. This regex will capture the numbers from zero to one hundred [baring any typos] (?<=s|^)(?:[0-9]+|(?:(?:twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety)s)?(?:one(?:[s-]hundred)?|two|three|four|five|six|seven|eight|nine)|ten|eleven|twelve|(?:thir|four|fif|six|seven|eight|nine)teen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|zero)(?=s|$) Live Example: http://www.rubular.com/r/EIa18nx731 Perl Example $string

Categories : Regex

regexp inverse mac-address match
With your original pattern you are starting a conditional (the (?(...) part), but without then/else clause. I am quite sure you didn't want this. Your second pattern has the problem, that you are checking a condition with your negated lookahead, but you don't match something. So change it to ^(?![0-9A-Fa-f]{12}$).*$ This will match any pattern that is not [0-9A-Fa-f]{12}.

Categories : Regex

How to get the second occurrence of a Regexp match in Javascript
Add the g flag to the end... re = /-?d+.d{6}/g; This g is for global. var matches = str.match(re); Note that this won't work quite like the above if you add capturing groups.

Categories : Javascript

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

VIM regexp copy exact match
Use a regular expression with anchors to the beginning and end of the line, do grouping to keep the numbers and replace the whole line with it. Run following command from the shell and it will create a new file output.txt with the numbers leaving the input file unmodified: vim -u NONE -N -c ' set backup | %s/v^D+(d+.d*).*$/1/ | saveas! output.txt | q! ' infile

Categories : Regex

Regexp javascript - url match with localhost
It depends on how complex you need the Regex to be. A simple way would be to just accept words (and the port/domain): ^https?://w+(:[0-9]*)?(.w+)?$ Remember you need to use the + character to match one or more characters. Of course, there are far better & more complicated solutions out there.

Categories : Javascript

RegExp: Match all comments that don't end with period
This negative lookbehind based regex should work for you: (?m)^//.*$(?<!.) OR negative lookahead based: (?m)^//(?!.*.$).*$ Live Demo: http://www.rubular.com/r/sUHNDokY2j

Categories : Regex

grep exact word match (-w) does not work with file paths in a text file
You can use egrep like this: egrep "(^| )$file1( |$)" "$file2" If file1="run" then above command will match string run preceded by line start or space and followed by space or line end.

Categories : Linux

Distinct,REGEXP apply to Field and CONCAT_GROUP in MYSQL to remove repeated words to stored procedure
No way with mysql for getting unique like this way. First it's bad that you storing values like this way. you have two solution: 1- Normalize your database. 2-get values from table and use php explode() , and use array_unique to remove duplicate values.

Categories : Mysql

Capture the match content of two different regexp in perl
There might be more clever ways, but I'd just break them up into separate statements: while (1) { $res1 = $string1=~m/(d+)/igs; $temp1 = $1; $res2 = $string2=~m/([^^]*?) +/igs $temp2 = $1; last unless $res1 == $res2; ... } Just because it's perl you don't have to find the most terse, cryptic way to write something (that's what APL is for).

Categories : Regex

Javascript RegExp match & Multiple backreferences
Your regex is literally looking for timequarterthe and splitting the match (if it finds one) into the three backreferences. I think you mean this: var test = /time|quarter|the/ig;

Categories : Javascript

MySQL RegExp how to match all given letters in any position
txa|tax|axt|atx|xta|xat Edit live on Debuggex Honestly, you can probably do it without "hard coding" it. However, the regex will prob be longer then this because there isn't many permutations of tax. ^(?=.*[t])(?=.*[x])(?=.*[a])[tax]{3}$ Edit live on Debuggex This is the actual not "hardcoded" way.

Categories : Mysql

How do I find the last occurrence of a match using regexp in MATLAB?
I am not sure what you are asking completely but you can edit the regexp function to return exactly what matches in a cell array. and Then with this cell array, simply chose the last index of it, which will be the last match. sectionEndIdx1 = regexp(str, expr,'match'); This will however, return the entire string you provided as a match, because based on the criteria you give your regular expression, it will match the entire string. If this is not the desired result, you will need to modify your regular expression string. I would suggest using a website like regexpal to test regular expressions before plugging them into MATLAB.

Categories : Regex

C++: Read individual lines from text file, sort words alphabetically
At least if I understand what you want correctly, I'd do something like this: Read a line into a string with std::getline. Initialize a std::stringstream from the string Read words from the stringstream into a vector Sort the vector Write the sorted words to the output. Repeat until done.

Categories : C++



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