w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
preg match from one keyword to another
You can use the s modifier that allow the dot to match newlines, or you can use this kind of pattern: $string =<<<LOD Telephone: 090866544 Address: 123 Hello Terrace Johnstown Ballamagoo Spain Comment: LOD; $pattern = '~Address:s*+K(?>S++|s++(?!Comment:))+~'; if (preg_match($pattern, $string, $match)) $result = $match[0]; Explanations: Address:s*+ K # reset all that have been matched before (?> # open an atomic group S++ # all that isn't a white character (space, tab, newline) | # OR s++(?!Comment:) # white characters not followed by "Comment:" )+ # close the group and repeat one or more times

Categories : PHP

preg match name not preg_matching
The expression isn't right, /^[a-zA-Z]+[a-zA-Z(). ]?+[a-zA-Z)]?+$/ You are saying: Start of string followed by a letter (any case) one or more times, followed by an (optional letter bracket dot or space) one or more times, followed by an (optional letter or bracket) one or more times then the end of the string. Not quite sure how it gets LLuffy, but the ?+ are just ... pointless, comment back or edit with what you are trying to match and I'll tell you.

Categories : PHP

php preg match parse something that could be a Youtube URL
Have you tried using greedy matching http://regex101.com/r/lT1wK5? Remember to escape the u also, otherwise you'll get Compilation failed: PCRE does not support L, l, N{name}, U, or u Example: $var = "u0026itag=22u0026url=http%3A%2F%2Fr5---sn-q4f7dnel.c.youtube.comu0026sig"; preg_match('/u0026itag=22\u0026url=(.*)/', $var, $A); echo $A[1];

Categories : PHP

preg match all in array searching for [ ]
You need to escape the opening square bracket because [147] is seen as a character class that contains 1, 4 and 7 You can do this with: $result=preg_grep('~^[14(?:7|8)]:~',$rgData); print_r($result); You can find all that you want to know about escaping (or not) square brackets here

Categories : PHP

Preg Match word and period before and after
preg_match_all('#(?<pre>w+) (title|loan) (?<post>w+)#',$html, $matches); will capture words before and after title|loan if they are separated by spaces. Easy enough to tweak if you need more flexible boundaries between your words. You can then access the matches by: foreach ($matches as $match) { echo $match['pre']; echo $match['post']; } To match everything between periods (sentences) that contain title|loan, you can do this: preg_match_all('#[^.]*(title|loan)[^.]*#', $html, $matches); This will match all characters that are not periods before and after title|loan.

Categories : PHP

How to get first possible match using preg match in php
Short answer: Yes you can. You need to use lazy quantifiers. So instead of preg_match("/[[test.*]]/i",$str,$match); use preg_match("/[[test.*?]]/i",$str,$match); to make the function stop at the first match. Note: if you want to match a literal [ or ]charactor you need to escape them like: [ or ]. After a little reaserch on php.net I discovered a pattern modifier U (PCRE_UNGREEDY) that will set the default for the pattern to lazy as apposed to greedy. So this means that preg_match("/[[test.*]]/iU",$str,$match); will also suit for this purpose. A note for this though: All *, +, ? in the regex will now try to match as few characters as possible.

Categories : PHP

proper way to pattern match with escaped char
This is the "canonical" regex which is $, but here this is a Java string. And in a Java string, a is written "\". Therefore: "123\$45" As to your target string, it just needs to be "123$45".

Categories : Java

How can I match a char at a specific index in a string?
if(myString.charAt(7)== '/') { // do stuff } else { // do other stuff } Putting a character in double quotes makes it a String. Single quotes makes it a char. And you compare characters with literal == whereas you compare Objects with the equals method

Categories : Java

Perl - Is this a bug with looks_like_number, or am I being a stupid person?
According to ikegami, You're probably using the Pure Perl version of Scalar::Util, which probably uses a regex, which clobbers $1. looks_like_number("$1") will fix it. Thanks! This fixed it.

Categories : Perl

Is my bash file stupid, can it be simplified?
First if it's for bash, use the proper header: #!/bin/bash No need to use cat, just use $(<): now=$(</sys/class/power_supply/BAT0/charge_now) full=$(</sys/class/power_supply/BAT0/charge_full) No need to use cat again since awk can accept input or parse files by itself: Wifi=$(awk 'NR==3 {print $3}' /proc/net/wireless) Quote your variables between "" properly: Batt=$(echo "$now $full" | awk '{ printf("%.2f ", $1/$2 * 100) }') Basically that's all I can see that's apparent. UPDATE As suggested by user000001, you could also use here strings: Batt=$(awk '{ printf("%.2f ", $1/$2 * 100) }' <<< "$now $full")

Categories : Bash

Extremely weird jQuery bug or am I just stupid?
You need to put the line: $('<input type = "text" value = "Test2">').appendTo('#container'); before your other jQuery. It's failing because the syntax you're using will only apply the code to elements already in the DOM. So you would need to add your element to the DOM first, and then apply the other code. jsFiddle example Or, use .on()'s delegation syntax like: $(document).on('focusin', 'input, textarea, select', function () { This will allow you to bind the events to any elements in the DOM already, and any elements you dynamically add later on. From the docs: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform eve

Categories : Javascript

The Stupid Assembly and Temp ASP.NET files story
The Temp folder is used for assembly shadow copying as described here. It is basically to avoid locking the assemblies and allow their in-place update.

Categories : C#

Stupid behavior of multi dimensional array
You need to add bounds checking. For instance when the user inputs the move coordinates you need to ensure they are within the range of 0 to 2. The example below validates the input to ensure only numbers are entered, that both X and Y coordinates are entered on a single line and that the coordinates are within range. It uses std::stringstream to parse the coordinates instead of having to deal with checking and clearing the fail bits on std::cin #include <string> // at top of your .cpp file #include <sstream> // in main() // Get en entire input line so we can skip extra characters // after the cell coordinates string inputLine; std::getline(cin, inputLine); stringstream inputStream(inputLine); if(!(inputStream >> X) || !(inputStream >> Y)) { cout << "

Categories : C++

Background wont display on view controller. Stupid issue?
Do a bit of research on float number equivalence. The changes of the height being exactly equal to 960 or 1136 is slim (though they could be). You should check for >= or <= instead. The chances of matching 960 pr 1136 is especially slim as they are the @2x sizes. The true size of the frame will be 480 or 568. So, try something like if (height > 481) and a simple else.

Categories : IOS

is char** x = (char**) arg equivalent to reinterpret_cast(const_cast(arg) )?
Yes they are basically the same except the c++ style cast shows the reader of the code that you are doing some weird stuff while its harder to notice with the c style. Its legal yet as always its highly suspect when a const incoming parameter is being cast as non const.

Categories : C++

How to select rows from character array that match char string and save them in a new array?
Try ismember(A(:, 1:numel(B)), B, 'rows') rather to get a logical vector that indexes only the rows you want and now A(C,:) to extract the rows The reason you're getting a dimension mismatch error is because your A(:,1:9) has many rows but B only has one and Matlab does not automatically broadcast like Octave or Python. You could do it using either repmat or bsxfun but in this case ismember is the correct function to choose.

Categories : Matlab

C++ Error: no match for call to ‘(std::string {aka std::basic_string}) (std::string&)’
You are attempting to assign the value of one string to another, which has already been initialized. The syntax for that is std::string s1 = ....; std::string s2 = ....; s2 = s1; // OK, assignment whereas you are attempting the equivalent of s2(s1); // error, this is no way to assign s1 to s2 and that is just invalid syntactically in this context. You cannot initialize objects that have already been constructed.

Categories : C++

Preg split table all tds
Using the DOMDocument class, you can easily get all cells like so: $dom = new DOMDocument; $dom->loadHTML($htmlString); $cells = $dom->getElementsByTagName('td'); $contents = array(); foreach($cells as $cell) { $contents[] = $cell->nodeValue; } var_dump($contents); The $cells var is a DOMNodeList, so it has some methods that you might be able to use. The $cell variable will be assigned a particular instance of DOMNode on each iteration, which has all sorts of methods/properties that could be useful for your use-case, too (like getAttribute) Looking at your question, though, you'll be wanting the outer html (including the tags) in your array. Now that's easy:" $markup = array(); foreach($cells as $cell) { $markup[] = $dom->saveXML($cell); } Side-note: Perhaps a for

Categories : PHP

preg replace for needed value
Sound like you want to do a preg_match: http://phpfiddle.org/main/code/z6q-a1d $old_vals = array( '33.4534543543<', '33.4534543543,', ', 33.4534543543<' ); $new_vals = array(); foreach ($old_vals as $val) { preg_match('(d*.?d+)',$val, $match); array_push($new_vals, $match[0]); } print_r($new_vals); Output Array ( [0] => 33.4534543543, [1] => 33.4534543543, [2] => 33.4534543543 )

Categories : PHP

Preg replace string in php
Try this: $pattern = '/([0-9]{2}/[0-9]{2}/[0-9]{4})/'; $replacement = ',$1'; $contents =preg_replace($pattern, $replacement, $contents); This adds comma before every date. If you want to change the whitespace to comma, then do this: $pattern = '/s([0-9]{2}/[0-9]{2}/[0-9]{4})/'; $replacement = ',$1'; $contents =preg_replace($pattern, $replacement, $contents);

Categories : PHP

preg replace multiple results
Do this with preg_replace_callback(): $txt = preg_replace_callback('#[code](.*)[/code]#isU', function($match) { return "<div class="bb_uncode">" . str_replace('[', '&#91;', $match[1]) . "</div>"); }, $txt);

Categories : PHP

Excel 2007 VBA MATCH function is not finding a match, but a match does exist in that range?
You must use MatchType of 0 to use wild card characters (* or ?) see: http://office.microsoft.com/en-001/excel-help/match-function-HP010062414.aspx Use Application.Match("More items related to*", Range("AZ1:AZ1000"), 0)

Categories : Excel

php preg replace missing some contents after replacement
You should use (.*?) echo preg_replace('/<li class="test_item test-item-45">(.*?)</li>/', 'test', $marr); in order to break match after the first </li> occurred

Categories : PHP

How can I write this php preg-replace lines shortly?
You don't need preg_replace() for this, you can use strtr() or str_replace() for this. Both allow you to specify a replacement array. Edit: a few years back I've spent considerable time on the development an I18N library that can handle languages with funny rules for sorting, etc, you might be interested in extending it for your language instead of writing your own code.

Categories : Misc

improve preg / pcre / regex to find PHP variable
simply use backreferences preg_match_all('/$(S+?)[;s=]/', $str, $matches); foreach ($matches[1] as $match) { // $match is now only the name of the variable without $ and ; }

Categories : PHP

preg replace not working with file_get_content - removing brackets() & replacing words
First example (bad): $array = array(""); $replace = array(""); // Please put the maximum number this (Page: maximum) for($i = 1; $i <= 1000; $i++) { array_push($array, "(Page: $i)"); // Put your replace string this or leave blank array_push($replace, "I am replaced :)"); } $file = 'I am (Page: 129) this is test.'; $new_string = str_replace($array, $replace, $file); echo $new_string; Second example (good). $file = 'I am (Page: 129) this is test.'; $new_string = preg_replace('(Page: ([0-9]+))', "", $file); $new_string = str_replace("()", "", $new_string); echo $new_string;

Categories : PHP

Templatized ostream overload ambiguity error : basic_ostream vs const char[]
The non-template operator does not cause any ambiguity because that operator itself is not viable for resolving this call: return out << "a1"; // ^^^^^^^^^^^ // This MUST be `std::operator <<`, no other valid overload of // operator << is found! As well as the other similar ones. The template version, on the other hand, is viable, since T is not bound to be any concrete type: template <class T> ostream& operator<<(ostream& out, const T& a) { switch(a) { case T::a1 : return out << "a1"; // ^^^^^^^^^^^ // Here the compiler could invoke std::operator << // OR it could invoke your operator << template, // which is also viable since T could be anything! //

Categories : C++

Unable to pass an address of array of type char *[2] to function taking char ***
char *array[2] = {"string", "value"}; is an array with 2 elements of char *. Using array as an address results to a pointer to the first element, i. e. of type char **. Using &array results to a pointer to the same place, but of type char *(*)[2] (not sure if the spelling is right). This is not the same as a char *** - the representation in memory is completely different. To be more verbose, +++++++++++++++++++++++ + array[0] + array[1] + +++++++++++++++++++++++ this is the array. char ** p1 = array; // is a pointer to the first element, which in turn is a pointer. char *(*p2)[2] = &array; // is a pointer to the whole array. Same address, but different type, i. e. sizeof(*p1) != sizeof(*p2) and other differences. char ***p3 = &p1; // Now, p1 is a different pointer va

Categories : C

How to disable type char in JTextArea but enable removed char (Backspace)
try to put DocumentFilter instead of DocumentListener something like final AbstractDocument abstractDocument = (AbstractDocument) textArea.getDocument(); abstractDocument.setDocumentFilter(new DocumentFilter() { @Override public void remove(final FilterBypass fb, final int offset, final int length) throws BadLocationException { super.remove(fb, offset, length); } @Override public void insertString(final FilterBypass fb, final int offset, final String string, final AttributeSet attr) throws BadLocationException { if (getLineCountAsSeen(textArea) < 4) { super.insertString(fb, offset, string, attr); }

Categories : Java

C - Sort char string in array to equal char user input
OK, so basically you want to convert a sorted array of letters to a specific (random?) ordering and record the swaps along the way, right? Here is one way to do this. #define SWAP(a,b) a^=b;b^=a;a^=b int main(int argc, char* argv[]) { char* wordInput=argv[1]; char* newWord = (char*)malloc((strlen(wordInput) + 1) * (sizeof(char))); int i,j,k; fprintf(stdout, "Word is %s ", wordInput); // Sort wordInput into newWord. for (i=0; i<strlen(wordInput); i++) { // Put this one at the end. newWord[i]=wordInput[i]; // Start at the back of the string, and move it forward if it is less. for (j=i-1; j>=0; j--) { if (newWord[j+1] < newWord[j]) { SWAP(newWord[j+1], newWord[j]); } else { break; } } } newWord[strlen(wordInput)]

Categories : C

char pointers, char arrays, and strings in the context of a function call
The char[] signature in the parameter is exactly the same as char*. In C++, it is illegal to convert a string constant char const* (the string "Kacy") to a char* because strings are immutable. Your second example compiles because the name is an actual array. There is no change to char*. As a solution, change your parameter to take a const string array: Student(char const name[]); which again is the same as String(char const *name); though you're better off using std::string: #include <string> class String { public: String(std::string name); };

Categories : C++

How can I write a function boolean succeeds(char a, char b, String s)? using s.equals(""), s.charAt(0), s.substring(1)
Something like this should work. I have not compiled this. Hopefully it gets you in the right direction, even with possible syntax errors. public boolean succeeds(char a, char b, String s){ boolean sawFirst= false; for(int i=0;i<s.length();i++){ if(!sawA){ if(s.charAt(i)==b) sawFirst = true; } else{ if(s.charAt(i)!=a) return false; else sawFirst= false; } } return true; }

Categories : Java

Printing the memory representation of an integer using char* and unsigned char*
This is because (on your system) char is signed, and it's getting promoted to int in the printf() call. Use unsigned char: void print_bytes(const unsigned char *ptr, size_t len) { for(size_t i = 0; i < len; ++i) { printf("%p %x ", ptr + i, ptr[i]); } }

Categories : C

How compare a char / single char string - with some list of alphabets set
If the starting letter is always an English character (or anything representable by a reasonably small integer that fits into an unsigned char), then here's a solution (the fastest possible one I can think of - uses no jumps except for the first check for initialization and only plain old integers are used instead of the somewhat heavier-weight comparison of NSString instances): - (UIColor *)colorFromName:(NSString *)name { static UIColor *strs[1 << CHAR_BIT] = { nil }; static BOOL initted = NO; if (!initted) { strs['a'] = [UIColor greyColor]; strs['b'] = [UIColor whiteColor]; // ... strs['z'] = [UIColor blueColor]; initted = YES; } unsigned char first = tolower([name characterAtIndex:0]); return strs[first]; }

Categories : IOS

Why does GCC accept convertion from 'const char *' to 'char *' on std::strrchr() returned value?
Actually your g++ does not accept the conversion from 'const char *' to 'char *', it's just that on your version std::strrchr() returns a char* (incorrectly, instead of a const char*). To verify the first part of my statement, try to compile the following on your GCC versions, I predict that all will correctly issue an error: int main() { const char* p = "foo"; char* q = p; // error, invalid conversion from 'const char*' to 'char*' } Now for the second part, I tried to compile the following minimal code, whose actual aim is to trigger an error in order to list the declared overloads of std::strrchr: #include <cstring> void (*p)() = &std::strrchr; // error here, with "candidates are: ..." int main() {} Well, with gcc 4.7.2 the message shows the expected "all non-c

Categories : C++

Regarding type safety when storing an unsigned char value in char variable
"does this mean that char could maintain its 'signedness' throughout the comparison?" yes; -1 as a signed char will be promoted to a signed int, which will retain its -1 value. As for the unsigned char, it will also keep its 255 value when being promoted, so yes, the comparison will be false. If you want it to evaluate to true, you will need an explicit cast.

Categories : C

What to call method which returns char* ( String in Java and char* in C++)?
It returns a String object and you can use the JNI string functions to convert that string to a char*: char* gPGGetName() { jobject objStr = env->CallObjectMethod(g_Obj, g_s3eGPGGetName); jsize len = env->GetStringUTFLength(objStr); const char* strPtr = env->GetStringUTFChars(objStr, 0); char* buffer = (char*)malloc((len + 1) * sizeof(char)); memcpy(buffer, strPtr, len); buffer[len] = ''; env->ReleaseStringUTFChars(objStr, strPtr); return buffer; }

Categories : Android

Unhandled Exception when converting const char to char
Both your contents of buff and buffA are in read-only memory of the process. You will actually need to new your buff like char* buff = new char[32]; This provides memory from the free-store and you can then strcat the string from buffA to buff. You should prefer strncat, though to avoid buffer-overruns and delete your buff eventually.

Categories : C++

how to convert c++ char read using "Marshal.ReadByte" to c# char?
Assuming the source char is using ASCII or Latin-1 (ISO 8859-1), in C# you'd do char ch = (char)Marshal.ReadByte(...);. This works because the ASCII and Latin-1 encodings are subsets of Unicode. A .NET char is a UTF-16 code unit, which will fit each of these fine with just a cast. If you think you'll deal with other source encodings, a better option may be to use Encoding.GetString() on a byte array. Keep in mind that some encodings require multiple units to encode a single code point (UTF-8, EUC-JP, Shift-JIS, etc.), so a single char may not be enough.

Categories : C#

Seg faulting on a car cast from unsigned char to const char in C++
Note that you cannot initialize a char* from a string literal in C++11. The clause which allowed that initialization in C++98 and C++03 was removed. If you worked out why that is, you have a hint on one thing which went wrong! You may want to read up on memory allocation as well or, better yet, use proper C++ facilities like std::string as raw pointer manipulators are fairly hard to get right.

Categories : C++



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