w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Using regex to match beginning and end of string [Java]
It is always good to think of what you are trying to do in english, before you create regular expressions. You want to match a word maze followed by a digit, followed by a literal period . followed by another word. word `w` matches a word character digit `d` matches a single digit period `.` matches a literal period word `w` matches a word character putting it all together into a single string you get (keep in mind the double backslash for the Java escape and the pluses to repeat the previous match one or more times): "\w+\d\.\w+" The above is the generic case for any file name in the format xxx1.yyy, if you wanted to match maze and in specifically, you can just add those in as literal strings. "maze\d+\.in" example: http://ideone.com/rS7tw1

Categories : Java

Match substrings and only keep the highest value
As I see from your comment, the information is coming from the database so do something like this: (pseudocode) SELECT group_id, MAX(points) FROM db_table GROUP BY group_id;

Categories : PHP

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

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

Substrings using regex grouping in C#
Try this: // string strTargetString = @"Acceptance :DT_Ext_0062-12_012ed2 [Describe]"; // string strTargetString = @"Acceptance : DT_Ext_0062-12_012 (ed.2) , Describe"; string strTargetString = @"Acceptance of : DT_Ext_0062-12_012 (ed.2) , Describe to me"; const string strRegex = @".*:s*(DT_Ext_d{4}-d{2}_d{3})s*W*(ed).?(d+)(W*[,])?(.*)"; RegexOptions myRegexOptions = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant; Regex myRegex = new Regex(strRegex, myRegexOptions); foreach(Match myMatch in myRegex.Matches(strTargetString)) { if(myMatch.Success) { // Add your code here var value = new { Value1 = myMatch.Groups[1].Value, Value2 = myMatch.Groups[2].Value, Value3 = myMatch.Groups[3].Value,

Categories : C#

Search for multiple RegEx substrings
Don't search for the pound sign. Search for the numbers, then manually add the pound sign yourself. import re strings = [ "5.20", "$5.20", "$.50", "$5", "Shipping is free", "Shipping: not specified", "free", "not specified", ] pattern = r""" d* #A digit 0 or more times [.]? #A dot, optional d+ #A digit, one or more times | free #Or the word free | not s+ specified #Or the phrase "not specified" """ regex = re.compile(pattern, flags=re.X) results = [] for string in strings: md = re.search(regex, string) if md: match = md.group() if re.search(r"d", match): match = "$" + match results.append(match) else:

Categories : Python

python regex match everything between defined word on the beginning of the line to defined word in other line
You are missing multiline mode. Otherwise ^ matches only at the beginning of the entire string. Also, you can avoid the (?:.| ) by using the singleline/dotall mode (which makes . match any character): start_tag = r'^ruledef ' #additional space char content = r'(.*?)' end_tag = r'#exit' ... for match in re.findall(start_tag + RD_name + content + end_tag, txt, re.M|re.S): ... Note that this will give you the contents of the ruledef (i.e. just the things that were matched by the content part - no ruledef, no name, no #exit). If this is not what you want, simply remove the parentheses incontent`: ... content = r'.*?' ... By the way, it might be more efficient to use a negative lookahead instead of an ungreedy quantifier (but it doesn't have to - ple

Categories : Python

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

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

To match pattern from beginning - Perl
Use the "^" match begin of line operator. #!/usr/bin/perl $mysub= "is"; $str="this good morning"; if($str=~ /^$mysub/){ print ("Here"); } else { print ("Not in it"); }

Categories : Perl

jquery autocomplete (NOT UI) , match beginning of the words
Have you looked at Typeahead? It has several options for matching and can potentially solve your problem. http://twitter.github.io/typeahead.js/examples/

Categories : Jquery

Is it possible to cut off the beginning of a string using regex?
I think this will work: var str = "/foo/bar/baz/hello/world/bla.html"; alert( str.replace( /^.*?(/[^/]*(?:/[^/]*)?)$/, "$1") ); This will allow for there being possibly only one last part (like, "foo/bar").

Categories : Javascript

preg_replace json string match same character beginning/end
Don't work on the json directly, decode it using json_decode(). Then cleanup your HTML using HTMLPurifier, which does a great job at cleaning HTML code. Then encode your data to json again using json_encode().

Categories : PHP

Regexp to match exactly one word in the beginning of the String in Java
You are just missing an anchor at the start. ^(\w+)\sis not (\w+) See it here at Regexr. ^ is anchoring the regex to the start of the string. If you don't do this it will match on the string "mary ann is not tall", but from "ann" on "mary ann is not tall"

Categories : Java

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

Regex: Accepting space anywhere but at the beginning
Does this not do what you want? import re re.match('^[^W].*[^W]$', ' aaa ') (Where the last arg is your test string). If you want to ensure the length is less than a certain amount use curly braces. One character is already spent testing the first and last chars of the test string with the inclusion of the [^W] notation. So in this example, there is a match when there are no spaces at either side and when the test string is no longer than 4 characters. re.match('^[^W].{1,2}[^W]$', 'aaaa')

Categories : C++

Regex at the beginning of a string in context
You need to move the anchor inside the lookbehind, like this: (?<=^[)[da-f]{8}(?=])" Otherwise, you wouldn't match [f000000f], because no part of your expression "consumes" the opening square bracket [.

Categories : C#

Regular expression match any character at the beginning end with specific string
Try this as a regex: /S+-line(?![-w])/ The word anchor is not suitable here since dashes are not considered part of a word, so /S+-line/ would mistakenly match text-with-line-not-to-be-replaced. Hence the lookahead construct. Of course, according to your use case, S may seem a little coarse. If your words really only consist of letters then dashes etc, then you can use the normal* (special normal*)* pattern: /[a-z]+(-[a-z]+)*-line(?![-w])/i (normal: [a-z], special: -) (edit: changed the lookahead construct, thanks to @thg435)

Categories : Javascript

RegEx that matching an expression NOT at the beginning of a line
If you are trying to match vol/vol./volume that is not at the beginning of a line, the following should work: ^.+(vol.?|volume) ^.+ means match 1 or more characters from the beginning of the line (vol.?|volume) means match vol followed by an optional . or match volume

Categories : Java

Regex for every group of spaces at the beginning of a line
Assuming your current font-lock rule looks like: (,highlight-indentation-current-regex (1 'highlight-indentation-face)) you could use (,highlight-indentation-current-regex (1 (if (save-excursion (skip-chars-backward " ") (bolp)) 'highlight-indentation-face)))

Categories : Regex

Oracle regex string not beginning with '40821'
According to this question, negative lookahead and lookbehind are not supported in Oracle. One way would be to explicitly enumerate the possibilities using alternation. In your case it would be something like: ^([012356789]|4[123456789]|40[012345679]|408[013456789]|4082[023456789])

Categories : Regex

Regex to match paths that don't match a specific pattern: Express Router
The following regex will match any path except those starting with /foo/ app.get(/^/([^f][^o][^o]|.{1,2}|.{4,})/.*$/, routes.index); I assume that this is a standard javascript regex.

Categories : Regex

Regular expression with positive lookbehind at beginning fails to match whole string
You really don't need to use a positive look-behind at all, >>> import re >>> find_decimal = re.compile(r'decimal((d+,d+))') >>> find_decimal.match('decimal(4,1)').group(1) '4,1' As for the reason it doesn't work, not sure but I'd guess you are correct in your thinking.

Categories : Python

Regex to convert spaces to tabs, but only at the beginning of a line
I couldn't find a regular expression that I could use on a whole file at a time, so I created a little script to recursively iterate through a directory and change each line of each php / js / css file individually, runs very fast though. Just cd to your directory and run the script. <?php $dir = getcwd(); $it = new RecursiveDirectoryIterator($dir); $ii = new RecursiveIteratorIterator($it); $files = new RegexIterator($ii, '#^(?:[A-Z]:)?(?:/(?!.Trash)[^/]+)+/[^/]+.(?:php|css|js)$#Di'); foreach ($files as $file) { $name = $file->getPath().'/'.$file->getFileName(); echo $name." "; $lines = file($file->getPath().'/'.$file->getFileName()); $length = count($lines); for ($i = 0; $i < $length; ++$i) { $lines[$i] = preg_replace('/G {2}/

Categories : Regex

Regex to match single new line. Regex to match double new line
To match exactly N repetitions of the same character you need lookaheads and lookbehinds (see Match exactly N repetitions of the same character). Since javascript doesn't support the latter, a pure regexp solution seems to be impossible. You'll have to use a helper function, for example: > x = "...a...aa...aaa...aaaa...a...aa" "...a...aa...aaa...aaaa...a...aa" > x.replace(/a+/g, function($0) { return $0.length == 2 ? '@@' : $0; }) "...a...@@...aaa...aaaa...a...@@"

Categories : Javascript

Regex to match only till first occurence of class match
You were missing ? Your regex would be (?i)(.*?)case[^a-zd]*(d+)(.*) You can toggle case insensitive match using (?i) in regex

Categories : Regex

Assets:precompile fails because a '/' character in .js file is interpreted as the beginning of a regex
The obvious but not necessarily best answer would be to split up that line some. this.x++; data[i] = Math.sin(this.x / (this.sample_rate / (this.frequency * 2 * Math.PI))); Or this.x++; var t1 = this.frequency * 2 * Math.PI; var t2 = this.sample_rate / t1; var t3 = this.x / t2; data[i] = Math.sin(t3); Though I'm sure there are better variable names based on the underlying equation. However, I am interested to see why this is happening. Does the JavaScript work locally?

Categories : Ruby On Rails

Remove occurrences of a given character sequence at the beginning of a string using Java Regex
Try something like this replace statement: yourString = yourString.replaceAll("(?i)^(\s*re\s*:\s*)+", ""); Explanation of the regex: (?i) make it case insensitive ^ anchor to start of string ( start a group (this is the "re:") \s* any amount of optional whitespace re "re" \s* optional whitespace : ":" \s* optional whitespace ) end the group (the "re:" string) + one or more times

Categories : Java

Regex that match if the match contains special word
You're kind of on the right track with lookahead assertions: {{START}}(?:(?!{{END}})[sS])*specialword(?:(?!{{END}})[sS])*{{END}} Explanation: {{START}} # Match {{START}} (?: # Match... (?!{{END}}) # ...as long as we haven't reached {{END}} yet: [sS] # any character )* # any number of times. specialword # Match "specialword" (?: # Match (as before)... (?!{{END}}) # whatever follows, unless it's {{END}} [sS] )* {{END}} # Then finally match {{END}}

Categories : Regex

Regex - Find the match that is inside a match
You can try this regex: /href=[^>]+.pdf/ regex101 demo Most of the time, when you can avoid .* or .+ (or their lazy versions), it's better :) Also, don't forget to escape periods.

Categories : PHP

Java regex: need one regex to match all the formats specified
Try using a reluctant quantifier: _year:.*?s. .replaceAll("_year:.*?\s", "_year:Y ") System.out .println("utc-hour_of_year:2013-07-30T17 dsfsdgfsgf utc-week_of_year:2013-W31 dsfsdgfsdgf" .replaceAll("_year:.*?\s", "_year:Y ")); utc-hour_of_year:Y dsfsdgfsgf utc-week_of_year:Y dsfsdgfsdgf

Categories : Java

Regex.Match() won't match a substring
Try removing ^ and $: Regex regex = new Regex(@"[ABCEGHJKLMNPRSTVXY]{1}d{1}[A-Z]{1} *d{1}[A-Z]{1}d{1}", RegexOptions.None); ^ : The match must start at the beginning of the string or line. $ : The match must occur at the end of the string or before at the end of the line or string. If you want to match only in word boundaries you can use  as suggested by Mike Strobel: Regex regex = new Regex(@"[ABCEGHJKLMNPRSTVXY]{1}d{1}[A-Z]{1} *d{1}[A-Z]{1}d{1}", RegexOptions.None);

Categories : C#

regex not returning match but there is clearly a match
You need to escape the dollar sign. start = '>$' end = '</td>' AnnualDiv = re.search('%s(.*)%s' % (start, end), s).group(1) The reason is that the $ is a special character in regex. (It matches the end of a string or before the newline.) This will set AnnualDiv to the string '0.48'. If you want to add the $, you can do it using this: AnnualDiv = "$%s" % re.search('%s(.*)%s' % (start, end), s).group(1)

Categories : Python

Redis HashKey erroring out
Well, I've looked locally, and it works fine. The main thoughts I have: are you in the correct database? (select in redis terms) is it possible that C: already had a non-hash value, and therefore the value could not actually be set in the first place? Calling any hash command (including hset) will fail if the value is not a hash - so if it already exists as a string: bad things are you checking the correct key? (noting that keys are case-sensitive) in particular, I notice that you aren't checked for errors; since BookSleeve is fully asynchronous, it cannot tell you about server-side errors when you call Set; any error will be exposed (when it arrives) via the Task API, via any of await, .Wait(), .Result or .ContinueWith() (or any other Task API of your choice) But locally: redis 127.0

Categories : C#

Javascript regex to match a regex
A regular expression to match a regular expression is //((?![*+?])(?:[^ [/\]|\.|[(?:[^ ]\]|\.)*])+)/((?:g(?:im?|mi?)?|i(?:gm?|mg?)?|m(?:gi?|ig?)?)?)/ To break it down, / matches a literal / (?![*+?]) is necessary because /* starts a comment, not a regular expression. [^ [/\] matches any non-escape sequence character and non-start of character group [...] matches a character group which can contain an un-escaped /. \. matches a prefix of an escape sequence + is necessary because // is a line comment, not a regular expression. (?:g...)? matches any combination of non-repeating regular expression flags. So ugly. This doesn't attempt to pair parentheses, or check that repetition modifiers are not applied to themselves, but filters out most of the other ways that regular expressions

Categories : Javascript

Looking for non-zero property TOs: Can I match a Description with number property, but use a regex match?
It is known that integer types has to be passed as integers in the description rendering the usage of regular expressions useless unfortunately. I do not have a QTP installation at hand right now, but to investigate it further, what happens if you use Print Browser("myBrowser").WebElement("height:=11").ChildObjects.Count and Print Browser("myBrowser").WebElement("height:=^[1-9][0-9]*$").ChildObjects.Count Where "myBrowser" is your browser definition of course.

Categories : Regex

Regex to match this
You can try this pattern: ^(?:[^e ]+|Be|e(?!xception))+.php:d+$ or this pattern, if you don't need to check a specific line format: ^(?>[^e ]++|Be|e(?!xception))+$ Notice: If you need to select all consecutive lines in one block, you just need to remove from the character classes.

Categories : Regex

Regex right match url with DOT at the end
The simplest fix is to require a non-punctuation character as the last character: /(^|[?s])(www.[^? ]+/[^/ ]*?[^? ]*[^?.,! ]|www.[^? ]*[^?.,! ])/g Note that I removed some of your backslash, because they were not necessary. JSFiddle. However, this is still by for not a robust URL pattern. So, why reinvent the wheel instead of just using some established URL pattern?

Categories : Javascript

Regex to match [] but not []
http://rubular.com/r/16q3jSPHN0 [^\](?:]?([(.+?)])) should work for most cases. Edit: Seems like this will not match [test][test], as Rory pointed out. For that, I can't really think of a good solution without using multiple regexps, but if you want just one then try this: http://rubular.com/r/QBqFAbqW9E (?:[^\](?:]?([(.+?)]))|((?:]?([(.+?)])))\) Match groups will be populated in the first 3 if it a block with escaped brackets occurs after a regular block, and the last 3 if the opposite occurs. Match 1 1. 2. 3. [test] 4. [test] 5. test Match 2 1. [test] 2. test 3. 4. 5.

Categories : Javascript

Regex match everything after
Why not using a mix of preg_match() and explode()?: $str = '/events/display/id/featured'; $pattern = '~/events/(?P<method>.*?)/(?P<parameter>.*)~'; preg_match($pattern, $str, $matches); // explode the params by '/' $matches['parameter'] = explode('/', $matches['parameter']); var_dump($matches); Output: array(5) { [0] => string(27) "/events/display/id/featured" 'method' => string(7) "display" [1] => string(7) "display" 'parameter' => array(2) { [0] => string(2) "id" [1] => string(8) "featured" } [2] => string(11) "id/featured" }

Categories : PHP



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