w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
regex match and replace multiple patterns
Use re.sub with $. target = ''' LINCOLN STREET CHESTNUT ST CHISHOLM TR LAKE TRAIL CHISHOLM TRAIL COVERED WAGON TRL ''' import re print re.sub('s+(STREET|ST|TRAIL|TRL|TR)s*$', '', target, flags=re.M)

Categories : Python

grep command on linux ( especially grep --exclude)
you can find grep on man pages here. what exclude does: --exclude=PATTERN: Recurse in directories skip file matching PATTERN. your command will search, recursively, in all directories, skipping file pattern "*.svn*" and searching for file pattern "1.0.0.8/*1.0.0.8.config > 1.0.0.8-REVISION.txt"

Categories : Linux

Match multiple patterns in unknow order with Expect.pm
set of devices That's the magic word. Use Set::Scalar. If $expect_devices->is_subset($known_devices), you have your "match".

Categories : Perl

Replace line with multiple trailing patterns
Here is an awk one liner: $ awk -F= 'NR==FNR{a[$1]=$0;next}$1 in a{$0=a[$1]}1' myfile.txt responsefile.txt '#'Please fill the user id details. '#'Here is example user=urname. user=myname '#'Please fill the details. '#'Here is example Was_WAS_AdminId=CN=wsadmin-xxxx. Was_WAS_AdminId=CN=wsadmin,OU=service,OU=WAS_Secure,OU=tb,ou=dcdc,ou=sysadm,dc=info,dc=prd,dc=dcdc The order of the two files in the command is important

Categories : Linux

RegEx - Exclude Matched Patterns
The negative lookahead, I believe is what you're looking for. Maybe try: (?!.*mak(e|ing) ?it ?cheaper) And maybe a bit more flexible: (?!.*mak(e|ing) *it *cheaper) Just in case there are more than one space.

Categories : Regex

Unix script to recursively search a directory and sub directories to grep and print content between 2 patterns in file
This might work for you: find . -type f -exec awk 'BEGING {print FILENAME ":"} /Pattern1/ { p=1 ; next } /Pattern2/ {p=0} p==1 {print $0} END {print ""}' {} ; Note, this prints the FILENAME, even if Pattern1 was not found!

Categories : Unix

grep regex return substring but exclude comments
This grep should work: grep -Po '^[^!].*?(?<=/)K[^/.]*(?=.)' infile.txt OUTPUT: baseline Explanation: ^[^!] will make sure to match anything but ! at line start K will make sure to reset the start

Categories : Regex

Why does enclosing a single char in brackets in a regex exclude the grep itself when grepping ps?
This is because the expression ba[s]h (or [b]ash, or...) just matches bash, not ba[s]h (or [b]ash, or...). So the grep command is looking for all lines with bash: root 2286 1 0 Jun06 ? 00:03:15 /bin/bash /etc/init.d/zxy100wd wmiller 6436 6429 0 Jun06 pts/0 00:00:01 bash wmiller 10707 6429 0 Jun07 pts/1 00:00:00 bash wmiller 10795 6429 0 Jun07 pts/2 00:00:00 bash but wmiller 16220 6436 0 06:55 pts/0 00:00:00 grep --color=auto ba[s]h does not match because it is not exactly bash.

Categories : Regex

Bash script to grep through one file for a list names, then grep through a second file to match those names to get a lookup value
awk -v search="$search_string" '$0 ~ search { gsub(/"/, "", $5); print $1" "$5; }' "$filename" | while read line do result=$(awk -v search="$line" '$0 ~ search { print $3; } ' "$lookup_file"); # Do "something" with $result done

Categories : Bash

Match Multiple Line Regex Javascript
You probably want to use JavaScript's String.prototype.match with /(?:Name.+)(?: .*){2}/g. The non-capture groups are so you don't double up your results. var s = ' Name: John Doe Address: 123 W Main Street City: Denver Name: Julie Smith Address: 1313 Mockingbird Lane City: Burbank '; var arr = s.match(/(?:Name.+)(?: .*){2}/g); /* gives ["Name: John Doe Address: 123 W Main Street City: Denver", "Name: Julie Smith Address: 1313 Mockingbird Lane City: Burbank"] */ // so if you want no new lines, arr.map(function (e) {return e.replace(/ /g, ' ');}); Edit Just looked at your fiddle, the reason it doesn't work is because you forgot to put in new lines. i.e. s = 'a b'; // s === "ab" s = 'a b'; // s === "a b"

Categories : Javascript

Match a structure against set of patterns
Actually, if I understood correctly, the fourth pattern is redundant, since the first pattern is more general, and includes every string that is matched by the fourth. That leaves only 3 patterns, which can be easly checked by this function: bool matches(const char* name, const char* email) { return strstr(name, "new_user") || strstr(name, "del_user") || strstr(email, "@gmail.com"); } And if you prefer to parse whole string, not just match the values of action and email, then the following function should do the trick: bool matches2(const char* str) { bool match = strstr(str, "action=new_user ") || strstr(str, "action=del_user "); if (!match) { const char* emailPtr = strstr(str, "email="); if (emailPtr) { match = strstr(emailPtr, "@g

Categories : C++

RegEx to match the patterns
Maybe something like this... /^[./:a-z]([0-9]+/)?[a-z]+[^?]*$/ Explained here... /^ # Start regex, and start matching [./:a-z] # starts with dot, slash, colon or a-z ([0-9]+/)? # optionally has multi-digit number followed by slash [a-z]+ # has one or more letters next [^?]* # has zero or more characters that are not `?` $/ # end of matching and end regex Hard to know the specifics of what you are aiming for Tests in... Coffeescript rex = /^[./:a-z]([0-9]+/)?[a-z]+[^?]*$/ for str in """ .domain .domain.com .domain.com/path .domain.com:443/path domain.com domain.com/path domain.com:443/path domain /path :443/path """.split /[ ]+/ console.log "Should be true - is #{if str.match rex then 'true ' else 'fals

Categories : Javascript

Incomplete match with AND patterns
If you code the destinction between ground terms and complex terms into the type system, you can avoid the runtime check and make them be complete pattern matches. type Num = int type Name = string type GroundTerm = | Con of Num | Var of Name type ComplexTerm = | Add of Term * Term | Sub of Term * Term | Mult of Term * Term | Div of Term * Term | Pow of Term * Term | Neg of Term and Term = | GroundTerm of GroundTerm | ComplexTerm of ComplexTerm let (|Operator|) ct = match ct with | Add(_) -> "+" | Sub(_) | Neg(_) -> "-" | Mult(_) -> "*" | Div(_) -> "/" | Pow(_) -> "**" let (|Unary|Binary|) ct = match ct with | Add(x, y) -> Binary(x, y) | Sub(x, y) -> Binary(x, y) | Mult(x, y) -> B

Categories : F#

notepad++ ( perl ) regex match multiple line pattern
Regex <div[^>]+>(.*?)</div> Don't forget to check the option . matches newline like in the image below : Alternatively, you can use this regex also: <div[^>]+>([sS]*?)</div> with or without the checkbox checked. Discussion Since * metacharacter is greedy, you need to tell him to take as few as possible characters (use of ?). Check that the divs you want to remove DO NOT contain nested div. In that case, the regex at the start of my answer won't help you. If you face this case, I'd suggest you using an html parser.

Categories : Regex

Priority in core.match patterns
As far as I know, core.match doesn't support regexes as match variables in any "special" way. That is, your first clause might match if text were actually a regex, but if it is a string matching a regex, it will fail.

Categories : Clojure

Need to match at least 3 of given patterns in Regular Expression
It might not be a good idea to use regex for password validation, but using lookaheads and the or operator | allows you to do this: ^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])|(?=.*[#$%=@!{},`~&*()'?.:;_|^/&#43;"-])(?=.*[a-z])(?=.*[0-9])|(?=.*[A-Z])(?=.*[#$%=@!{},`~&*()'?.:;_|^/&#43;"-])(?=.*[0-9])|(?=.*[A-Z])(?=.*[a-z])(?=.*[#$%=@!{},`~&*()'?.:;_|^/&#43;"-])).{8,32}$ There are 4 parts in this regex: (?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]) Makes sure there's at least 1 lower alpha, 1 upper alpha and 1 number. (?=.*[#$%=@!{},`~&*()'?.:;_|^/&#43;"-])(?=.*[a-z])(?=.*[0-9]) Makes sure there's at least 1 special character, 1 upper alpha and 1 number. (?=.*[A-Z])(?=.*[#$%=@!{},`~&*()'?.:;_|^/&#43;"-])(?=.*[0-9]) Makes sure there's at least 1 upper alph

Categories : Regex

Php Regex: how to match repeated patterns
Here you go: $data = explode(" ", $data); $out = array(); foreach ($data as $d) { preg_match_all('/s(d+)/', $d, $matches); Puts $matches[0] equal to an array of matches. You then want to add it to the array of rows: $out[] = $matches[0]; } You now have an jagged array of lines and columns. So, to reference line two column four, you can go to $out[1][3].

Categories : PHP

How to match a tree against a large set of patterns?
This paper describes a variant of the Aho–Corasick algorithm, where instead of using a finite state machine (which the standard Aho–Corasick algorithm uses for string matching) the algorithm instead uses a pushdown automaton for subtree matching. Like the Aho-Corasick string-matching algorithm, their variant only requires one pass through the input tree to match against the entire dictionary of S. The paper is quite complex - it may be worth it to contact the author to see if he has any source code available.

Categories : Algorithm

How can I share match patterns between keys?
I'd define a general entity with the pattern, and refer to it from the two locations. So the stylesheet would begin <!DOCTYPE xsl:stylesheet [ <!ENTITY match-elements "p | p-cont | heading[not(parent::section or parent::contents) and not(parent::p)] | language-desc | country-desc | graphic[not(parent::section or parent::contents)] | block-quote | bulleted-list | blank-line | bibliography | language-name-index | language-code-index | country-index | table-of-contents"> ]> <xsl:stylesheet ...> ... And the two key uses would be: <xsl:key name="narrow-things-by-columnset" match="&match-elements;" use="sileth:columnset-id(.)"/> <!-- DONE: DRY: Isn't is nice to be able to share the above match pattern instead

Categories : Xslt

Does grep process line by line or entire file?
EDIT: I will correct myself. It is neither line by line nor full file, its in terms of chunks of data which are placed into the buffer. More details are here http://lists.freebsd.org/pipermail/freebsd-current/2010-August/019310.html

Categories : Unix

Get the contents of a line by line number in perl, awk, grep
This is how to print a single line given a line number With awk: $ awk 'NR==314' file If you file is large you may want to quit after reaching the line: $ awk 'NR==314{print;exit}' file You could also use sed for this: $ sed '314!d' file Equally: $ sed -n '314p' file With sed to print a line by number and quit you would do: $ sed -n '314{p;q}' file The perl solution will be similar to the awk solution however I don't know/use perl myself. This can not be done with grep unless you use nl or cat -n firts. However you can print the line numbers of lines matching the given pattern with grep using the -n option. From man grep: -n, --line-number (-n is specified by POSIX.) Prefix each line of output with the 1-based line number within its

Categories : Perl

How to replace all matching patterns only if it does not match another pattern?
Use a negative lookbehind to achieve your goal: String regex = "(?<!:)%s"; It matches %s only if there is not a : right before it.

Categories : Java

Split line comma at end of line and exclude special cases
Matching a comma at the end of the string is done with an anchor: /,$/m The /m modifier is used to enable multiline mode, in which $ will match the end of the line instead of the standard end-of-subject.

Categories : Regex

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

Grep variable pattern match
Your multiple commands with pipes can be simply replaced with the awk itself. Use following script: SOMETHING=$(awk '/^ something/{print substr($4, 1, 3);}' somefile.conf) if [ "$SOMETHING" = "123" ]; then echo "Found 123" else echo "Cannot find 123" && exit 1 fi EDIT: Looks like you've edited the question and your script after I posted my anser. Here is the modified awk command for you latest edit (don't do it again pls): SOMETHING=$(awk -F "." '/^ something/{split($1, a, " "); print a[2]}' somefile.conf)

Categories : Linux

Chrome-extension URL match patterns:Why rules are not working for Google.com?
You need to include a wildcard * to your matches like so: "content_scripts": [ { "matches": ["https://www.google.com/*", "http://www.google.com/*"], "js": ["static/js/jquery.js", "static/js/contentscript.js"] } ],

Categories : Ajax

Match empty lines in a file Grep
grep and count empty lines like this: grep -c "^$" myfile.txt As is considered end of line you need to use line start and line end "^$"

Categories : Regex

Regex Exclude match
Use a negative look ahead: ((?!^.*iPad.*$)Mobile)|iP(hone|od)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune

Categories : Regex

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

Using NamedParameterJdbcTemplate, how to retrieve record sets from sql server that match a list of regex patterns
I figured out a way to achieve it. Thanks guys. StringBuilder sb = new StringBuilder(); for(String str1 : valuesForBuildingPatterns1) for(String str2 : valuesForBuildingPatterns2) sb.append(" col1 LIKE '%" + str1 + "%' AND col2 LIKE '%" + str2 + "%' OR"); sb.delete(sb.length()-2, sb.length()); String sqlQuery = "SELECT * FROM sqlServerTable WHERE" + sb.toString(); resultset = namedParameterJdbcTemplate.query(sqlQuery, params, new MyRowMapper());

Categories : Regex

Regular Expression - Match But Exclude?
Here's an easy way: string sampleText = "<i>This should be in italics</i> but this ¶ character needs to be removed"; string sPattern = "(</?i>)|[―&<>♫♪–‧₢₳-⅓⅟□¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶•¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕ×ØÙÚÛÜÝÞßàáãäåæçèéêëìíîïðñòóôö÷øùüýþÿŒœŠšŸŽžƒ˜-‰›¢€°]"; string replacePattern = "$1"; string text = Regex.Replace(sampleText, sPattern, replacePattern, RegexOptions.IgnoreCase); Console.WriteLine(text); // <i>This should be in italics</i> but this character needs to be removed But this will only work with <i> and </i> tags. You can expand that to other tags pretty easily (e.g. "(</?w+>)|..."

Categories : C#

Spring security: A universal match pattern ('/**') is defined before other patterns in the filter chain, causing them to be ignored.
The problem was in the regex of classpath in the context-param. <param-value> classpath:**/sampler-context.xml classpath:**/sampler-security.xml </param-value> Changing it to <param-value> classpath*:sampler-context.xml classpath*:sampler-security.xml </param-value> solves this problem.

Categories : Spring

Regex with grep - match unknown number of alphabetical characters?
Have a look at the manual. Without the -E flag, grep assumes "basic" regular expressions. In this case most meta-characters lose their special meaning, unless you escape them. So do grep -nr "STRINGONE_w+_w+_STRINGTWO" or grep -nrE "STRINGONE_w+_w+_STRINGTWO" Or, since you only want uppercase letters: grep -nr "STRINGONE_[A-Z]+_[A-Z]+_STRINGTWO" grep -nrE "STRINGONE_[A-Z]+_[A-Z]+_STRINGTWO" Otherwise, strings with three or more components in the middle would also be accepted.

Categories : Regex

How do I filter to match or exclude certain fields in Octave?
You can use cellfun to go through the cell array and get an index (binary): octave> cellfun (@(x) x(1) == 1 || x(2) > 3, A) ans = 1 0 1 1 1 0 Using your example: octave> A(cellfun (@(x) x(1) == 1 || x(2) > 3, A)) ans = { [1,1] = 0 5 32 [2,1] = 1 4 13 [3,1] = 1 2 32 [4,1] = 2 7 99 } An alternative which may be faster is to ditch the cell array completely and use a matrix instead (as long as each cell in the cell array have the same size, a matrix makes a lot more sense, even if you need to create a multi-dimensional matrix). That's likely to be much faster and simpler to read: octave> B = cell2mat (A); octave> B(B(:,1) == 1 | B(:,2) > 3, :) ans = 0 5 32 1 4 13

Categories : Linux

regex - match brackets but exclude them from results
Just keep the braces out of your capturing group: [([^]]+)] You have two arrays because one is the full match of your regex and the other what has been captured by the ().

Categories : Regex

Regex: How to match two character but exclude a certain combination
You can use a negative look-ahead. You can find more information on what that is here. Essentially, it "looks ahead" and ensures that the regex in the parentheses is not matched. DataFile_(?!en)w{2}.dat Note that you should be escaping that period, as it will match any character.

Categories : Python

How to exclude a row based on a partial string match?
How about: . . . WHERE keywords LIKE '%portraits%' AND keywords NOT LIKE '%outdoors%' . . . A better approach might be to define a separate table of keywords for jobs. It would have one row for each job/keyword combination. With proper indexing, you can greatly speed up the lookup of jobs with or without matching keywords.

Categories : Mysql

Plotting three densities on the same graph in different line patterns with titles etc
Appendix A of 'An Introduction to R' has a nice walkthrough tutorial you can do in ten minutes; it teaches among other things about line types etc After that, plotting densities was explained dozens of times here too; search in the search box above for eg '[r] density'. There is also the R Graph Gallery (possibly down right now) and more. A nice, free guide I often recommend is John Verzani's simpleR which stresses graphs a lot and will teach you what you need here.

Categories : R

"grep"ing first 12 of last 24 character from a line
One way with GNU sed (without counting dots): $ sed -r 's/.*(.{11}).{12}/1/' file 0.41207E-09 Similarly with GNU grep: $ grep -Po '.{11}(?=.{12}$)' file 0.41207E-09 Perhaps a python solution may also be helpful: python -c 'import sys;print " ".join([a[-24:-13] for a in sys.stdin])' < file 0.41207E-09 I'm not sure your example data and question match up so just change the values in the {n} quantifier accordingly.

Categories : Shell

grep for a string in a line if the previous line doesn't contain a specific string
I think you're better off using an actual programming language, even a simple one like Bash or AWK or sed. For example, using Bash: ( previous_line_matched= while IFS= read -r line ; do if [[ ! "$previous_line_matched" && "$line" == *xyz* ]] ; then echo "$line" fi if [[ "$line" == *jkl* ]] ; then previous_line_matched=1 else previous_line_matched= fi done < input_file ) Or, more tersely, using Perl: perl -ne 'print if m/xyz/ && ! $skip; $skip = m/jkl/' < input_file

Categories : Unix



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