w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Replace words of a sentence with formatted html
Use regexp and replace : var errors = ["Altough", "stil", "kdi"]; var regExp = new RegExp('\b('+errors.join('|')+')\b', 'gi'); var text = text.replace(regExp, '<span class="error">$1</span>'); Fiddle : http://jsfiddle.net/uezjK/4/

Categories : Javascript

regex to capture any several words in a sentence
Here's a regex that matches 1 to 3 words between the words "key" and "has", and here's a link to a RegExr that tests it. I admit I'm not familiar with spamassassin but if all you need it a regex to match a line of text then this should work: key(s((w+s){1,3})has Using the braces {1,3} means that the previous token (in this case, the group (w+s)) must match at least once but no more than three times. The  token matches a word boundary, and s matches any whitespace. w, as you know, matches any alphanumeric character. If you need to, you can use backreferencing to extract group 1, which now contains the words between "key" and "has" (as well as the whitespace surrounding them). Hope this helps!

Categories : Regex

Regex to match words in sentence after a pattern
Maybe the regex should be: How much is (.*)? Or if you want to match all the words but one word in each capture: How much is (?:(w+)s*)+? Regex regexWords = new Regex(@"How much is (?:(w+)s*)+?"); foreach(Capture word in regexWords.Match(input).Groups[1].Captures) { // word.Value contains one word. } Good luck with your quest.

Categories : C#

Tagging words/phrases in a sentence based on Regex match in Perl
Using your own dump with a simple for to iterate with the 2 arrays: #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $text = 'zzzzzzz microRNA146a xxx (miR-146a, mir-33c) xxxx microRNA146a wwwwww Breast Cancer aaaa Breast Cancer zzzz mir-33c kkk'; # Rule 1 for miRNA definition my $i = 0; $text =~ s/(mir-dw+|micrornad+w?)/"[$1]<MIR-" . $i++ . ">"/gie; # Rule 2 for special words/phrases my $j = 0; $text =~ s/(breast cancer)/"[$1]<CANCER-" . $j++ . ">"/gie; print $text; Live DEMO.

Categories : Regex

Using ucwords and explode to ignore hyphens and capitalise words in php
Use str_replace('-', ' ', $subdomain) before calling ucwords to replace - with a space. For example: <?php $subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST'])); echo ucwords(str_replace('-', ' ', $subdomain)); ?>

Categories : PHP

Match a part of a sentence and replace white space in that sentence
The most straightforward and probably most efficient way to do this is to just use two regular expressions, however if the language you are using allows for using a function as the replacement then you can do this with one call. For example with Javascript: var s = '123456 ABC - 14 days there are eels in my hovercraft [blablabla]' var regex = /^.*days *| [.*$|( )/g; var result = s.replace(regex, function (match, p1) { return p1 ? '+' : ''; }); Example: http://jsfiddle.net/5fsEA/ Same approach using Python: import re s = '123456 ABC - 14 days there are eels in my hovercraft [blablabla]' result = re.sub(r'^.*days *| [.*$|( )', lambda m: '+' if m.group(1) else '', s)

Categories : Regex

How to change the color the words between two specific words in a sentence
I am not going to bother iterating and parsing your string thats trivial. SpannableString span1 = new SpannableString("pravind "); SpannableString span2 = new SpannableString("kumar"); span1 .setSpan(new ForegroundColorSpan(Color.BLUE), 5, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); span2.setSpan(new ForegroundColorSpan(Color.RED), 5, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mTextView.setText(TextUtils.concat(span1," " ,span2));

Categories : Java

Using jquery/JS/CSS how do I append words to a sentence so the sentence is pushed up word by word
You can use element div inside the paragraph. The div should have a width or a left-margin It can looks like this http://jsfiddle.net/wmqFL/3/. If you want you can creae the div dynamically.

Categories : Javascript

Trying to spit sentence into array with words
Your code seems to be working fine. Make sure you're getting the variable. You can do a print_r($_GET); You can also just do this: <?php $_GET['check'] = 'Hey how are you?'; if (isset($_GET['check'])) { // each word is now an element in the array $arr = explode(' ', trim($_GET['check'])); } // piece each word back together with a space echo implode(' ', $arr); ?> It doesn't matter if it's a single word or multiple words. UPDATE: If you really want to check if the user has entered one word or more than one word you can do this: <?php $_GET['check'] = 'Hey how are you?'; if (str_word_count($_GET['check']) > 1) { echo 'More than one word'; } else { echo 'Only one word'; } ?> Check out str_word_count

Categories : PHP

Sentence generator with words from lists
You need a third random number and phrase, to select the second name to be used. For example: // Generate two random numbers int rand1 = (int) (Math.random() * nameLength); int rand2 = (int) (Math.random() * actionLength); int rand3 = (int) (Math.random() * nameLength); String phrase1 = name[rand1]; String phrase2 = action[rand2]; String phrase3 = name[rand3]; System.out.print("It is obvious that" + ' ' + phrase1 + " " + "is a better" + " " + phrase2 + " " + "than" + " " + phrase3 + "!" ); Edit: To avoid the possibility of having the same name selected for both phrase1 and phrase3, the following code should ensure that a different index is used for selecting phrase3 than phrase1: int rand1 = (int) (Math.random() * nameLength); int rand2 = (int) (Math.

Categories : Java

Reversing order of words in a sentence
You can use std::string std::vector and std::reverse to make things easier: std::string sentence = "Your sentence which contains ten words, two of them numbers"; std::stringstream stream(sentence); std::vector<std::string> words; for ( std::string word; stream >> word; ) { words.push_back(word); } Now you have everything separated into words. You may now want to remove question marks or other punctuation, since the logic will be easier to implement while the words are still in the correct order. For reversing, do this: std::reverse(words.begin(), word.end()); You'll need to include several headers: #include <string> // for storing strings in a C++ way #include <sstream> // to easily separate sentences into words #include <vector> // to dynamically s

Categories : C++

Remove duplicate words from the sentence in C
Disclaimer: This will not fix your algorithm, see @Rohans answer for the fix in your algorithm. To fix your code, do the following: *output = (char*) malloc(text_size); ... should be: char *output = malloc(text_size); ... and change: *output[0] = ''; ... to be: output[ 0 ] = ''; ... do not cast a malloced block of memory. You can read more about this here. Observe that output[ 0 ] implies *( output + 0 ). Next, change: strcpy(*output, element); ... to: strcpy(output, element); ... then change: if (strstr(*output, element) == NULL) { strcat(*output, " " ); strcat(*output, element ); } ... to: if (strstr(output, element) == NULL) { strcat(output, " " ); strcat(output, element ); } ... notice that output is already a pointer, using the * as you do dereferen

Categories : C

javascript break sentence by words
Just use split: var str = "This is an amazing sentence."; var words = str.split(" "); console.log(words); //["This", "is", "an", "amazing", "sentence."] and if you need it with a space, why don't you just do that? (use a loop afterwards) var str = "This is an amazing sentence."; var words = str.split(" "); for (var i = 0; i < words.length - 1; i++) { words[i] += " "; } console.log(words); //["This ", "is ", "an ", "amazing ", "sentence."] Oh, and sleep well!

Categories : Javascript

Python extracting sentence containing 2 words
If this is what you mean: import re txt="I like to eat apple. Me too. Let's go buy some apples." define_words = 'some apple' print re.findall(r"([^.]*?%s[^.]*.)" % define_words,txt) Output: [" Let's go buy some apples."] You can also try with: define_words = raw_input("Enter string: ") Check if the sentence contain the defined words: import re txt="I like to eat apple. Me too. Let's go buy some apples." words = 'go apples'.split(' ') sentences = re.findall(r"([^.]*.)" ,txt) for sentence in sentences: if all(word in sentence for word in words): print sentence

Categories : Python

Regular Expression for a specific set of words in a sentence
Description This expression will match the your phrases, and ensure they are not embedded inside another larger word. ^.*?(?:s|^)(ofstheshouse|time|thississhow|home)(?=W|$).* PHP Code Example: You didn't specify a language so I'm just providing this php example to simply show how this works. Sample Text 1) "I was coming out of the house" 2) "I remember the time when I used to be a baby" 3) "Well, I am not sure what you did, but this is how I fix my problems" 4) "When are you coming home?" 5) "This is howard Timey said of the houseboat" 6) "The last word in this line is home Code <?php $sourcestring="your source string"; preg_match_all('/^.*?(?:s|^)(ofstheshouse|time|thississhow|home)(?=W|$).*/imx',$sourcestring,$matches); echo "<pre>".print_r($matches,true); ?> Mat

Categories : Regex

Counting co-occurrences of 2 words in a sentence (java)
I am not sure if I understood your requirements fully, but if you just need the count, you could give a weight to the strings in the list. For example if you have the entries artificial -> 1 intelligence -> 1 artificial intelligence -> -1 if the sentence contains "artificial intelligence", all three will match giving a sum of the weights = 1. This will need some preprocessing to calculate the correct weights for the strings.

Categories : Java

How to reverse words of sentence in a linked list?
Read each word and add it as a char array to a node. Then read your linked list from end to start. You'll get reversed sentence. ------------------------------- + *prev + "This" + *next + ------------------------------- ------------------------ + *prev + "is" + *next + ------------------------ ------------------------ + *prev + "an" + *next + ------------------------ ----------------------------- + *prev + "example" + *next + ----------------------------- Now read from the end using *prev.

Categories : C

Find words or sentence from a richtextbox and add into a list C#
Have you tried this?: string stringToSearch = "whatever"; if (Array.IndexOf(searching, stringToSearch.ToLower()) > -1) { //String found } Note that I included "ToLower()" because I understand that you want a match without caring about caps. This is a much quicker option to find matches than what you are using. Nonetheless, bear in mind that what you intend to do is impossible: you are dividing the content in a textbox into its constituent elements and then you look for this whole content in each of them. For example: the textbox has 1*safda*32, you divide it into "1", "safda" and "32" and then you intend to locate "1*safda*32" in "1", in "safda", etc. I see two options: Creating a list with suggestions for the user. That is, the contents in the array searching or in the list

Categories : C#

Initializing words of a sentence stored in a string into UILabels
Your problem is this line: xVal=+200; This is the same as saying xVal = 200; the plus sign means positive 200 rather than 200 more. Try this instead: xVal += 200;

Categories : IOS

Convert Sentence array into words in batch Script
BAT language does not have the notion of arrays. You might however mimic it with various techniques. One such technique is making use of the automatic parsing of parameters passed in a CALL command. read HELP SET and HELP CALL and try this... SET sentence=matt_george_phil SET sentence=%sentence:_=% CALL :asarray %sentence% goto :eof :asarray echo first element = %1 echo second element = %2 echo third element = %3

Categories : Batch File

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

Python - split sentence after words but with maximum of n characters in result
I'd look at the textwrap module: >>> text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!' >>> from textwrap import wrap >>> wrap(text, 16) ['Hello, this is', 'an example of', 'text shown in', 'the scrolling', 'display. Bla,', 'bla, bla!'] There are lots of options you can play with in the TextWrapper, for example: >>> from textwrap import TextWrapper >>> w = TextWrapper(16, break_long_words=True) >>> w.wrap("this_is_a_really_long_word") ['this_is_a_really', '_long_word'] >>> w = TextWrapper(16, break_long_words=False) >>> w.wrap("this_is_a_really_long_word") ['this_is_a_really_long_word']

Categories : Python

putting words of a sentence into different transparent labels when a button is clicked
NSString *sentence = @"i am a boy"; NSMutableArray *words = [sentence componentsSeparatedByString:@" "]; CGFloat xVal = 0.0; for( NSString *word in words ) { UILabel *wordLabel = [[UILabel alloc] initWithFrame:CGRectMake(xVal,0,200,40)]; wordLabel.backgroundColor = [UIColor clearColor]; wordLabel.textColor = [UIColor blackColor]; wordLabel.text = word; xVal+=200; [self.view addSubview:wordLabel]; }

Categories : IOS

Remove some words replace some other words from a txt file
This should do the trick. You use a list to store the objects you want to delete, and then loop through the list and remove every element in the list from the contents string. Then, you use a dictionary to store the words you have now and the words you want to replace them with. You also loop over those and replace the current words with the replace ones. def replace(): contents = "" deleteWords = ["the ", "and ", "in "] replaceWords = {"ancient": "old", "month":"years", "centuries":"years"} with open("meText.txt") as f: contents = f.read() for word in deleteWords: contents = contents.replace(word,"") for key, value in replaceWords.iteritems(): contents = contents.replace(key, value) return contents

Categories : Python

I need a regex to select words from given list of words.
Finally I found something ^((man1|man2|man3|man4)(,(man1|man2|man3|man4)){0,3})?$ only problem is I cant restrict duplicating. Any suggestion to restrict duplicating?????

Categories : Misc

Regex for one word in sentence
The main problem is that . includes spaces. You need to change your .'s to be restricted to word-characters only, i.e. w. Note that w is (mostly) [A-Za-z0-9_], if you wish to exclude some of these or include more, you should make the appropriate changes. Another thing is that if you're looking for words in a string, you need to remove ^ and $ because these mean the start and end of the string respectively. Since all your requirements are "at least" (as opposed to "at most"), you don't really need  because of matching happens left-to-right, so you can never get part of a word. Regex: (?=w*d)(?=w*[a-z])(?=w*[A-Z])w+ Test.

Categories : Regex

Replace multiple strings with a single sentence
You're overwriting strReplaced in each loop run. It seems like you want this instead: for(i=0; i<=4; i++) { desc = desc.Replace(BadCharacters[i], GoodCharacters[i]); } Label1.Text = desc;

Categories : C#

How to replace the first word from each sentence (from input file)
You should use hasSet class it has remove method so ı hope this mini example help you My text: The a a dssfdsfd The a the an fdfdggth gtrfhtrht a the The fdsfddg My output: [fdfdggth, dssfdsfd, fdsfddg, gtrfhtrht] public class deneme { private static HashSet<String> hS = new HashSet<String>(); public static void main(String[]args) throws IOException { int loc=0; String line=""; File input=new File ("C:\deneme\inputstack.txt"); Scanner scanner=new Scanner(input); File output=new File("Hello2.java"); PrintStream print=new PrintStream(output); while (scanner.hasNext()) { if (scanner.hasNextDouble()) { Double doubleValue = scanner.nextDouble(); }

Categories : Java

Objective c - sentence validation regex
I agree with @borrrden that this is a difficult task for a regex, but one thing you'd need to do is to escape the regex-backslashes (for want of a better word) with another backslash (). Like this: NSString *regex1 = @"^[\w:;()'"\s-]*"; The reasoning behind this is that you want the regex engine to "see" the backslash, but the compiler which handles the NSString also uses backslashes to escape certain characters. "w" and "s" are not among those characters, so they w and s are just translated into w and s, respectively. A double backslash in a literal string serves to get a single backslash into the compiled string.

Categories : IOS

How to replace the letters in a lengthy sentence after a specific width
from http://css-tricks.com/snippets/css/truncate-string-with-ellipsis/ .truncate { width: 250px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

Categories : CSS

PHP Regex to find first n characters and finish it until end of sentence
Assuming you can delimit the end of a sentence by one of ., ?, or !: $output = preg_replace('/(^.{0,249}[^!?.]*.).*$/s', '$1', $string); Updated Demo (Added s modifier to work with multiline strings).

Categories : PHP

Replace persian or arabic sentence to randomly generated english
There is nothing like an "arabian tag" or something on strings which you could evaluate. Instead you'd have to define a detection routine yourself, though that should not be too difficult: In php you get the requested url (/arti/19029/متی-نتها-نیبتی/new in your example) inside the superglobal $_SERVER var. You can disect it using a regular expression (take a look at the preg_match() function) and extract those portions of the string that match certain characteristics. In your case you'd have to look for a certain range of characters inside the string, namely arabian characters. Things get much easier if that arabian part of the string always occurs at the same position inside the requested url. Then you don't have to check for certain characters but can use a simpler patter

Categories : PHP

regex last word in a sentence ending with punctuation (period)
By using the $ operator you will only get a match at the end of a line. So if you have multiple sentences on one line you will not get a match in the middle one. So you should just use: (w+). the capture group will give the correct match. You can see an example here

Categories : Java

Python regex: how to match strings that DO NOT contain an *exact* sentence?
Use a negative lookahead assertion like this: re.findall("(?!^.*This is message 12345. Ignore..*$).*", data) and also enable the m modifier, so that ^ and $ match the start and the end of a row.

Categories : Python

How can I use regex to search inside sentence -not a case sensitive
If you're just looking for strings containing a space, as your example indicates, it should be something like this: [i for i in ListSentence if i.endswith('®') or (' ' in i)]

Categories : Python

Java regex to remove multiple occurrences of a pattern from a sentence
Your regular expression replaces * (asterisk followed by two spaces) but not * *. If I read your request correctly, you need to group before the quantifier: (\*\s){2,} which says "astrisk followed by space, at least two times".

Categories : Java

Converting a sentence to an array and delete characters and print new sentence
Consider the following line: char c = zinArray[i]; Assigning copies the value (or the reference, in case of a class instance). So you have created a copy of the character at zinArray[i]. This means that changing the value of the variable c will not change the value stored in zinArray[i]. You have to perform the change to the array item, like this: zinArray[i] = (char)(c + 32);

Categories : Java

Replace multiple regex into one regex in perl
You can do it like this: message =~ s# &lt; (?<tag>span|em|ul|ol) &gt; (.*?) &lt; / k<tag> &gt; # <$+{tag}> $2 </$+{tag}> #xg;

Categories : Regex

Dotted line between two sentence but sentence is fixed width
Remove position:absolute from .bg .left and instead add display:inline-block to reestablish block context which allows a width to be set on your spans (which by default are inline elements and thus don't respect width declarations). Also you should change to float:right on your .bg .left:before. Your fixed Example

Categories : HTML

Extracting out a text variable in a sentence template to be replace by a random text
You can use replaceAll(String regex, String replacement) from String. See javadoc http://docs.oracle.com/javase/6/docs/api/java/lang/String.html String str = text.replaceAll(pattern, "text"); ; You can do this for all your vars, or better yet, use Matcher and Pattern It is described very thoroughly in this blog

Categories : Java



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