w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to write regex to match URL;s?
You can use this : ^/jsp/offer/recr/us/wsj/recoffertemp2flow1.jsp?offerId=d+&promoCode=d+$ But note that this regex would fail if you change the argument order.

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

How to write a regex in python to match this?
You need to add the python regex for whitespace into your pattern to account for the newlines. Try this: regex = r"[1-9]+) .*s.*" s is the regex for any whitespace

Categories : Python

How do I write a regex to match and capture at the same time?
What you are looking for is puts "line#{$1}". The pseudo-globals $1, $2, $3, etc. refer to capture groups of the last Regexp match. (And $~ refers to the MatchData itself, if you'd like to work with that.)

Categories : Ruby

Find characters that match a regex's set
Yes, you need to capture: final Pattern pattern = Pattern.compile("w_p([a-z])"); final Matcher m = pattern.matcher(input); if (m.find()) // what is matched is in m.group(1)

Categories : Java

Javascript regex: How to find length of a match?
If your regular expression has the g flag, you can execute it over and over again, getting all matches from the string, including the length of the match: var re = /^( |[ ]{4})/g; var match; while((match = re.exec(text)) { // use match.index and match[0].length }

Categories : Javascript

Java Regex find() vs match() usage
Use String.split(String regex): String line = "[0r(1)2[000p[040qe1w3h162[020t*882*11/11/2010*12:26*"; String[] parts = line.split("\*"); String date = parts[2]; String time = parts[3]; System.out.println("date=" + date + ", time=" + time); Output: date=11/11/2010, time=12:26

Categories : Java

Java Regex: find a match only at the beginnings of words
You have to use a Pattern: final Pattern p = Pattern.compile("\bAbc"); // ... if (p.matcher(input).find()) // match FYI,  is the word anchor. Java's definition for a word character is the underscore, a digit or a letter.

Categories : Java

How to use regex match to find a string in an array of patterns?
How about using join to make an impromptu regex? my @matches = ("cat", "zebra", "apple"); my $rx = join "|", @matches; while (<$fh>) { if ($_ =~ /$rx/) { # stuff } }

Categories : Perl

Is it possible to create a regex that will find strings that DO NOT match a pattern?
Sure thing, boss /(?!_PROCESSED)/ This is a negative lookahead and it's supported in almost all regexp flavours I've adapted an answer from this question to further help you. public static File[] listFilesMatching(File root, String regex) { if(!root.isDirectory()) { throw new IllegalArgumentException(root+" is not directory."); } final Pattern p = Pattern.compile(regex); // careful: could also throw an exception! return root.listFiles(new FileFilter(){ @Override public boolean accept(File file) { return p.matcher(file.getName()).matches(); } }); } listFilesMatching(new File("/some/path"), "(?!_PROCESSED)") Here's the docs for FileFilter

Categories : Java

Conflicting records when recording time taken to for regex to to find a match
When using the IsMatch() method instead of Matches(), the code does not create a large amount of objects that need to be collected (and probably are collected when you see the performance hits). I seem to be getting quite consistent results this way.

Categories : C#

Find all lines that match regex pattern and grab part of string
You can do something like this(no need of regex): Use str.startswith to check if a line starts with '\': >>> strs = "\BTLCMOODY01 MRA Server " >>> strs.startswith('\') True Then use a combination of str.split and str.lstrip to get the first word: >>> strs.split(None, 1) ['\BTLCMOODY01', 'MRA Server '] #apply str.lstrip on the first item >>> strs.split(None, 1)[0].lstrip('\') 'BTLCMOODY01' Code: >>> with open('abc1') as f: ... for line in f: ... if line.startswith('\'): #check if the line startswith `` ... print line.split(None,1)[0].lstrip('\') ... TESTHOSTDEV01 TESTHOSTDEVDB01 TESTHOSTDEVDBQA TESTHOSTDEVQA02 BTLCMOODY01 BTLCSTG05 BTLCWEB02 BTLCWSUS01 HIMSAPP01 SLVAPP01 TORAAPP01 HNSVA

Categories : Python

Find sublist of strings that match a regex that requires ordered inclusion from another list
I don't think Regex is necessary: >>> lst = [ 'foo-yes-bar', 'hello foo fine bar'] >>> strings_to_match = ['foo', 'bar', 'hello'] >>> [x for x in lst if all(s in x for s in strings_to_match)] ['hello foo fine bar'] >>> However, if you want to use Regex, I guess this would work: [x for x in lst if all(re.search(s, x) for s in strings_to_match)] Edit: Oh, well, since you want to respect order, you can do this: [x for x in lst if re.search(".*".join(map(re.escape, strings_to_match)), x)] My post though was geared towards your original question.

Categories : Python

Find match of string in Regex, put into variable, tricky string
What you are after is (as in regular expression): {BaseClass.(?<inheritClassStr>.*?),Tuple.Create("(?<machineStateStr>.*?)",string.Empty)} to clarify: d that you used will math only numbers but identifiers in C# tend to contain letters as well. .* would math any character in greedy manner (so the more the better) so it is not a good choice here .*? will math any character but in not greedy manner (so as small set as possible) And there is no magic in C# so your declarations in regex wont get converted to variables but you need to access those like this: var inheritClassString = regex.Groups["inheritClassStr"].Value; And the @ on the beginning of string just indicates that c# compiler wont try to interpret special characters that can be put in otherwise not prefixed st

Categories : C#

Trying to find a regex match for lowercase characters, but ignore first 11 characters
try ^.{11}[^a-z]*[a-z]+ conceptually, this pattern skips 11 characters at the beginning of a line, matches an arbitrary number of non-lowercase characters finally matching at least 1 lowercase char. complement the first chracter class with characters you do not want to occur in matching line.

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

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

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

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

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

How to find exact match using PSLIST and FIND in Batch/CMD
How about using the -e parameter of pslist? pslist -e notepad It will set errorlevel to 0 when found, and 1 when not found. Also it is an exact match meaning it will not identify notepad++. PSList Help pslist v1.3 - Sysinternals PsList Copyright (C) 2000-2012 Mark Russinovich Sysinternals - www.sysinternals.com Usage: pslist [-d][-m][-x][-t][-s [n] [-r n] [\computer [-u username][-p password][name|pid] -d Show thread detail. -m Show memory detail. -x Show processes, memory information and threads. -t Show process tree. -s [n] Run in task-manager mode, for optional seconds specified. Press Escape to abort. -r n Task-manager mode refresh rate in seconds (default is 1). \computer Specifies remote compu

Categories : Batch File

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

How to find with lookahead in Visual studio 2012 Regex Find and Replace
You need to add a (?s), which enables multiline matching, and also escape the period in using Example.Foo. The regex should be something along the lines of: (?s)using Example.Foo;(?=.*BaseClass<SomeClass>)

Categories : Regex

Match BOL and EOL with std::regex
libstdc++ has no full support for regex (you can check it here). I'm tried to compile this code with clang 3.2 with libc++-3.2 and result is "true". Use libc++, or boost. Especially libstdc++ regex implementation status 8 Regular expressions 28.1 General N 28.2 Definitions N 28.3 Requirements N 28.4 Header <regex> synopsis N 28.5 Namespace std::regex_constants Y 28.6 Class regex_error Y 28.7 Class template regex_traits Partial 28.8 Class template basic_regex Partial 28.9 Class template sub_match Partial 28.10 Class template match_results Partial 28.11 Regular expression algorithms N 28.12 Regular expression Iterators N 28.13 Modified ECMAScript regular expression grammar N

Categories : C++

Match a^xb^x with regex
The \1 is a backreference and refers to the value of the group, not to the pattern as the recursion (?1) does in Perl. Unfortunately, Java regexes do not support recursion, but the pattern can be expressed using lookarounds and backrefs.

Categories : Java

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

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

Given regex does not match to the end
You need to pass the global modifier. I'm not sure which programming language you are using, but the syntax often resembles the following: /$myregex/g For example, given the following text: Hello Adam, how are you? Hello Sarah, how are you? The regular expression /Hellos(.*),/g will match both Adam and Sarah.

Categories : Python

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 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

How to match two characters with regex
Use String#match() with the simple regex /@(w+)/ var dauto = function(){ $( '#capture' ).html($( this ).val().match(/@(w+)/)[1]); } $("textarea").bind("keyup",dauto); $("textarea").bind("keydown",dauto); Test with the following HTML block <textarea></textarea> <p id="capture"></p> Working Demo at JsFiddle.net (try typing "hi @username" there)

Categories : Javascript

Java Regex does not match
You can use this pattern to check whether an M character appears as at the beginning of the string: if (line.matches("M.*")) But for something this simple, you can just use this: if (line.length() > 0 && line.charAt(0) == 'M')

Categories : Java

Match last occurence with regex
You can use in greedy quantifier with a reduced character class (assuming you have no tags between you <br>): <br>([^<]*)<br>s*$ or <br>((?:[^<]+|<(?!br>))*)<br>s*$ to allow tags inside. Since the string you search is Tizi Ouzou without <br> you can extract the first capturing group.

Categories : Python

Regex - Match Last Occurance
You can try this:- .+((fsa|fwb|fcc).+)$ + matches many characters in front. ((fsa|fwb|fcc) matches and captures the keywords. .+) matches and captures characters. $ matches the end of the line. EDIT:- As suggested by m.buettner RegexOptions.RightToLeft should work for your case.

Categories : Dotnet

Check if a given regex will match anything
This doesn't exactly answer your question, but hopefully explains a little why a simple answer is hard to come by: First, the term 'regex' is a bit murky, so just to clarify, we have: "Strict" regular expressions, which are equivalent to deterministic finite automatons (DFAs). Perl-compatible regular expressions (PCREs), which add a bunch of bells and whistles such as lookaheads, backreferences, etc. These are implemented in other languages too, such as Python and Java. Actual Perl regular expressions, which can get even more crazy, including arbitrary Perl code, via the ?{...} construct. I think this problem is solvable for strict regular expressions. You just construct the corresponding DFA and search that graph to see if there's any path to a non-accept state. But that doesn't help

Categories : Regex

In Ruby 1.9, should the regex /c?ab/ match "cab" or "ab" first?
The regex as a whole is eager — it will try to match in the very first place it can. So c?ab and c??ab are equivalent: the only difference is in how long a substring they prefer to match, and they don't actually get the chance to exercise that preference. To expand a bit on this . . . consider this: /<.*>/.match("abcde<fghi>jkl<mn>o") It will start matching at the first <, and because it's greedy, it will try to match as much as possible while still matching, which means it will match <fghi>jkl<mn>. If you change to a non-greedy quantifier: /<.*?>/.match("abcde<fghi>jkl<mn>o") it will still start matching at the first <, but will now try to match as little as possible while still matching, which means it will match just &

Categories : Ruby

Regex match UK postcode
Wrap your regex in ^ and $ to ensure that full string is matched: var re = /^(GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(d[dA-Z]?[ ]?d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?d{1,4})$/; console.log(re.test('WD4 9PL')); ^ matches beginning of the line $ matches end of the line Note, I've also wrapped it in (): /^abc|def$/ will match abc.... and ....def /^(abc|def)$/ will match only abc or def Example: > /abc/.test("abcd") true > /^abc$/.test("abcd") false

Categories : Javascript



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