I am new to regular expression. I am trying to construct a regular expression that
first three characters must be alphabets and then the rest of the string could be any character. If the part of the string after first three characters contains & then this part should start and end with ".
I was able to construct ^[a-z]{3}, but stuck at conditional statement.
For example abcENT and abc"E&T" are valid strings but not abcE&T.
Can this be done in a single expression?
In most regex flavors, you may use simple lookaheads to make sure some text is present or not somewhere to the right of the current locations, and using an alternation operator | it possible to check for alternatives.
So, we basically have 2 alternatives: there is a & somewhere in the string after the first 3 alphabets, or not. Thus, we can use
^[A-Za-z]{3}(?:(?=.*&)".*"|(?!.*&).*)$
See the regex demo
Details:
^ - start of string
[A-Za-z]{3} - 3 alphabets
(?:(?=.*&)".*"|(?!.*&).*) - Either of the two alternatives:
(?=.*&)".*" - if there is a & somewhere in the string ((?=.*&)) match ", then any 0+ characters, and then "
| - or
(?!.*&).* - if there is no & ((?!.*&)) in the string, just match any 0+ chars up to the...
$ - end of string.
In PCRE, or .NET, or some other regex flavors, you have access to the conditional construct. Here is a PCRE demo:
^[A-Za-z]{3}(?(?=.*&)".*"|.*)$
^^^^^^^^^^^^^^^^^
The (?(?=.*&)".*"|.*) means:
(?(?=.*&) - if there is a & after any 0+ characters...
".*" - match "anything here"-like strings
| - or, if there is no &
.* - match any 0+ chars from the current position (i.e. after the first 3 alphabets).
A conditional statement could be use with | and groups, but it probably will be complicated.
^[a-z]{3}([^&]*$|".*"$)
You might think about using plain old string manipulation for this task, it probably will be simple
Yeah this is possible, it is not really an if, but in your case you can make an "or" with regex capturing Group. Your regex would look something like that:
\d{3}(\".*\"|[^&]*)
P.S. here is a good site to test and learn These things:
https://regex101.com/
The expression itself will depend on the regexp parser you'll use. If you're using Python, shell, vim, boost, etc. , the same symbol could have different meanings.
I would try the following :
$ echo 'abc"&def"' | grep -E "^[a-zA-Z]{3}(\".*\&.*\"|[^&]*)"
abc"&def"
Regular expressions don't necessarily support conditionals as in 'if', to achive this in a general case you have to state your conditions as alternatives. (But see Wiktor's comment, depending on your regex engine there might be conditionals available.)
For a relatively basic solution you might try something like this:
^[a-z]{3}([^&]*|\..*\.)$
Which says "After four letters, there should be a string of any length with no ampersand (&) OR a string starting and ending with a full stop (.).
Related
My regex pattern looks something like
<xxxx location="file path/level1/level2" xxxx some="xxx">
I am only interested in the part in quotes assigned to location. Shouldn't it be as easy as below without the greedy switch?
/.*location="(.*)".*/
Does not seem to work.
You need to make your regular expression lazy/non-greedy, because by default, "(.*)" will match all of "file path/level1/level2" xxx some="xxx".
Instead you can make your dot-star non-greedy, which will make it match as few characters as possible:
/location="(.*?)"/
Adding a ? on a quantifier (?, * or +) makes it non-greedy.
Note: this is only available in regex engines which implement the Perl 5 extensions (Java, Ruby, Python, etc) but not in "traditional" regex engines (including Awk, sed, grep without -P, etc.).
location="(.*)" will match from the " after location= until the " after some="xxx unless you make it non-greedy.
So you either need .*? (i.e. make it non-greedy by adding ?) or better replace .* with [^"]*.
[^"] Matches any character except for a " <quotation-mark>
More generic: [^abc] - Matches any character except for an a, b or c
How about
.*location="([^"]*)".*
This avoids the unlimited search with .* and will match exactly to the first quote.
Use non-greedy matching, if your engine supports it. Add the ? inside the capture.
/location="(.*?)"/
Use of Lazy quantifiers ? with no global flag is the answer.
Eg,
If you had global flag /g then, it would have matched all the lowest length matches as below.
Here's another way.
Here's the one you want. This is lazy [\s\S]*?
The first item:
[\s\S]*?(?:location="[^"]*")[\s\S]* Replace with: $1
Explaination: https://regex101.com/r/ZcqcUm/2
For completeness, this gets the last one. This is greedy [\s\S]*
The last item:[\s\S]*(?:location="([^"]*)")[\s\S]*
Replace with: $1
Explaination: https://regex101.com/r/LXSPDp/3
There's only 1 difference between these two regular expressions and that is the ?
The other answers here fail to spell out a full solution for regex versions which don't support non-greedy matching. The greedy quantifiers (.*?, .+? etc) are a Perl 5 extension which isn't supported in traditional regular expressions.
If your stopping condition is a single character, the solution is easy; instead of
a(.*?)b
you can match
a[^ab]*b
i.e specify a character class which excludes the starting and ending delimiiters.
In the more general case, you can painstakingly construct an expression like
start(|[^e]|e(|[^n]|n(|[^d])))end
to capture a match between start and the first occurrence of end. Notice how the subexpression with nested parentheses spells out a number of alternatives which between them allow e only if it isn't followed by nd and so forth, and also take care to cover the empty string as one alternative which doesn't match whatever is disallowed at that particular point.
Of course, the correct approach in most cases is to use a proper parser for the format you are trying to parse, but sometimes, maybe one isn't available, or maybe the specialized tool you are using is insisting on a regular expression and nothing else.
Because you are using quantified subpattern and as descried in Perl Doc,
By default, a quantified subpattern is "greedy", that is, it will
match as many times as possible (given a particular starting location)
while still allowing the rest of the pattern to match. If you want it
to match the minimum number of times possible, follow the quantifier
with a "?" . Note that the meanings don't change, just the
"greediness":
*? //Match 0 or more times, not greedily (minimum matches)
+? //Match 1 or more times, not greedily
Thus, to allow your quantified pattern to make minimum match, follow it by ? :
/location="(.*?)"/
import regex
text = 'ask her to call Mary back when she comes back'
p = r'(?i)(?s)call(.*?)back'
for match in regex.finditer(p, str(text)):
print (match.group(1))
Output:
Mary
My regex pattern looks something like
<xxxx location="file path/level1/level2" xxxx some="xxx">
I am only interested in the part in quotes assigned to location. Shouldn't it be as easy as below without the greedy switch?
/.*location="(.*)".*/
Does not seem to work.
You need to make your regular expression lazy/non-greedy, because by default, "(.*)" will match all of "file path/level1/level2" xxx some="xxx".
Instead you can make your dot-star non-greedy, which will make it match as few characters as possible:
/location="(.*?)"/
Adding a ? on a quantifier (?, * or +) makes it non-greedy.
Note: this is only available in regex engines which implement the Perl 5 extensions (Java, Ruby, Python, etc) but not in "traditional" regex engines (including Awk, sed, grep without -P, etc.).
location="(.*)" will match from the " after location= until the " after some="xxx unless you make it non-greedy.
So you either need .*? (i.e. make it non-greedy by adding ?) or better replace .* with [^"]*.
[^"] Matches any character except for a " <quotation-mark>
More generic: [^abc] - Matches any character except for an a, b or c
How about
.*location="([^"]*)".*
This avoids the unlimited search with .* and will match exactly to the first quote.
Use non-greedy matching, if your engine supports it. Add the ? inside the capture.
/location="(.*?)"/
Use of Lazy quantifiers ? with no global flag is the answer.
Eg,
If you had global flag /g then, it would have matched all the lowest length matches as below.
Here's another way.
Here's the one you want. This is lazy [\s\S]*?
The first item:
[\s\S]*?(?:location="[^"]*")[\s\S]* Replace with: $1
Explaination: https://regex101.com/r/ZcqcUm/2
For completeness, this gets the last one. This is greedy [\s\S]*
The last item:[\s\S]*(?:location="([^"]*)")[\s\S]*
Replace with: $1
Explaination: https://regex101.com/r/LXSPDp/3
There's only 1 difference between these two regular expressions and that is the ?
The other answers here fail to spell out a full solution for regex versions which don't support non-greedy matching. The greedy quantifiers (.*?, .+? etc) are a Perl 5 extension which isn't supported in traditional regular expressions.
If your stopping condition is a single character, the solution is easy; instead of
a(.*?)b
you can match
a[^ab]*b
i.e specify a character class which excludes the starting and ending delimiiters.
In the more general case, you can painstakingly construct an expression like
start(|[^e]|e(|[^n]|n(|[^d])))end
to capture a match between start and the first occurrence of end. Notice how the subexpression with nested parentheses spells out a number of alternatives which between them allow e only if it isn't followed by nd and so forth, and also take care to cover the empty string as one alternative which doesn't match whatever is disallowed at that particular point.
Of course, the correct approach in most cases is to use a proper parser for the format you are trying to parse, but sometimes, maybe one isn't available, or maybe the specialized tool you are using is insisting on a regular expression and nothing else.
Because you are using quantified subpattern and as descried in Perl Doc,
By default, a quantified subpattern is "greedy", that is, it will
match as many times as possible (given a particular starting location)
while still allowing the rest of the pattern to match. If you want it
to match the minimum number of times possible, follow the quantifier
with a "?" . Note that the meanings don't change, just the
"greediness":
*? //Match 0 or more times, not greedily (minimum matches)
+? //Match 1 or more times, not greedily
Thus, to allow your quantified pattern to make minimum match, follow it by ? :
/location="(.*?)"/
import regex
text = 'ask her to call Mary back when she comes back'
p = r'(?i)(?s)call(.*?)back'
for match in regex.finditer(p, str(text)):
print (match.group(1))
Output:
Mary
My regex pattern looks something like
<xxxx location="file path/level1/level2" xxxx some="xxx">
I am only interested in the part in quotes assigned to location. Shouldn't it be as easy as below without the greedy switch?
/.*location="(.*)".*/
Does not seem to work.
You need to make your regular expression lazy/non-greedy, because by default, "(.*)" will match all of "file path/level1/level2" xxx some="xxx".
Instead you can make your dot-star non-greedy, which will make it match as few characters as possible:
/location="(.*?)"/
Adding a ? on a quantifier (?, * or +) makes it non-greedy.
Note: this is only available in regex engines which implement the Perl 5 extensions (Java, Ruby, Python, etc) but not in "traditional" regex engines (including Awk, sed, grep without -P, etc.).
location="(.*)" will match from the " after location= until the " after some="xxx unless you make it non-greedy.
So you either need .*? (i.e. make it non-greedy by adding ?) or better replace .* with [^"]*.
[^"] Matches any character except for a " <quotation-mark>
More generic: [^abc] - Matches any character except for an a, b or c
How about
.*location="([^"]*)".*
This avoids the unlimited search with .* and will match exactly to the first quote.
Use non-greedy matching, if your engine supports it. Add the ? inside the capture.
/location="(.*?)"/
Use of Lazy quantifiers ? with no global flag is the answer.
Eg,
If you had global flag /g then, it would have matched all the lowest length matches as below.
Here's another way.
Here's the one you want. This is lazy [\s\S]*?
The first item:
[\s\S]*?(?:location="[^"]*")[\s\S]* Replace with: $1
Explaination: https://regex101.com/r/ZcqcUm/2
For completeness, this gets the last one. This is greedy [\s\S]*
The last item:[\s\S]*(?:location="([^"]*)")[\s\S]*
Replace with: $1
Explaination: https://regex101.com/r/LXSPDp/3
There's only 1 difference between these two regular expressions and that is the ?
The other answers here fail to spell out a full solution for regex versions which don't support non-greedy matching. The greedy quantifiers (.*?, .+? etc) are a Perl 5 extension which isn't supported in traditional regular expressions.
If your stopping condition is a single character, the solution is easy; instead of
a(.*?)b
you can match
a[^ab]*b
i.e specify a character class which excludes the starting and ending delimiiters.
In the more general case, you can painstakingly construct an expression like
start(|[^e]|e(|[^n]|n(|[^d])))end
to capture a match between start and the first occurrence of end. Notice how the subexpression with nested parentheses spells out a number of alternatives which between them allow e only if it isn't followed by nd and so forth, and also take care to cover the empty string as one alternative which doesn't match whatever is disallowed at that particular point.
Of course, the correct approach in most cases is to use a proper parser for the format you are trying to parse, but sometimes, maybe one isn't available, or maybe the specialized tool you are using is insisting on a regular expression and nothing else.
Because you are using quantified subpattern and as descried in Perl Doc,
By default, a quantified subpattern is "greedy", that is, it will
match as many times as possible (given a particular starting location)
while still allowing the rest of the pattern to match. If you want it
to match the minimum number of times possible, follow the quantifier
with a "?" . Note that the meanings don't change, just the
"greediness":
*? //Match 0 or more times, not greedily (minimum matches)
+? //Match 1 or more times, not greedily
Thus, to allow your quantified pattern to make minimum match, follow it by ? :
/location="(.*?)"/
import regex
text = 'ask her to call Mary back when she comes back'
p = r'(?i)(?s)call(.*?)back'
for match in regex.finditer(p, str(text)):
print (match.group(1))
Output:
Mary
I have this regular expression
([A-Z], )*
which should match something like
test, (with a space after the comma)
How to I change the regex expression so that if there are any characters after the space then it doesn't match.
For example if I had:
test, test
I'm looking to do something similar to
([A-Z], ~[A-Z])*
Cheers
Use the following regular expression:
^[A-Za-z]*, $
Explanation:
^ matches the start of the string.
[A-Za-z]* matches 0 or more letters (case-insensitive) -- replace * with + to require 1 or more letters.
, matches a comma followed by a space.
$ matches the end of the string, so if there's anything after the comma and space then the match will fail.
As has been mentioned, you should specify which language you're using when you ask a Regex question, since there are many different varieties that have their own idiosyncrasies.
^([A-Z]+, )?$
The difference between mine and Donut is that he will match , and fail for the empty string, mine will match the empty string and fail for ,. (and that his is more case-insensitive than mine. With mine you'll have to add case-insensitivity to the options of your regex function, but it's like your example)
I am not sure which regex engine/language you are using, but there is often something like a negative character groups [^a-z] meaning "everything other than a character".
trying to get the following regex: <- bad english from me :(
I'm trying to get the following input text converted as regex...
xx.*.aaa.bbb*
where * are wildcards .. as in .. they represent wildcards to me .. not regex syntax.
Any suggestions, please?
Update - example inputs.
xx.zzzzzzzzz.aaa.bbb = match
xx.eee.aaa.bbbzzzz = match
xx.eee.aaa.bbb.zzzz = match
xx.aaa.bbb = not a match
You misunderstood the concept of * in Regular Expressions.
I think what you are looking for is:
xx\..*\.aaa\.bbb.*
The thing is:
a . is not a real .. It means any character, so if you want to match a . you must escape it: \.
* means that the character that preceeds it will be matched 0 or many times, so how to emulate the wildcard you are looking for? Using .*. It will match any character 0 or many times.
If you want to match exactly the entire string, and not any substring that matches the pattern, you have to include ^ at the begining and $ at the end, so your regex will be:
^xx\..*\.aaa\.bbb.*$
Try this expression:
^xx\.[^\.]+\.aaa\.bbb.*
Assuming that you're saying that * is a wildcard in the 'normal sense', and that your string isn't an attempt at regex, I'd say that xx\..+\.aaa\.bbb.+ is what you're after.
What you refer to as "wildcard -- not regex syntax" is from globbing. It's a pattern matchnig technique that was popularized in the first Unix version in the late 60's. Originally it was a separate program -- called glob -- that produced a result that could be piped to other programs. Now bash, MS-Dos and almost any shell has this feature built-in. In globbing * normally means match any character, any number of times.
The regex syntax is different. The .* idiom in regex is similar to the * in globbing, but not exactly the same. Normally, .* doesn't match line-breaks. You usually have to set the single-line mode (in Ruby called multi line) if you want .* to match any character, any number of times in regex.
* are not wildcards, they mean the preceeding character is repeated 0 or 1 or many times.
And the dot can be any character.
UPDATE:
You can try this
^xx\.[a-z]+\.aaa\.bbb\.?[a-z]*
and you can test it for example here online on rubular
The [a-z] are character groups, within you can define what character is allowed (or not allowed using [^a-z]). so if you are only looking for lowercase letters then you can use [a-z].
The + means it has to there at least once.
The \.? near the end means there can be a dot or not
The ^ at the beginning means to match at the start of the string
A nice tutorial (for Perl, but at least the basics are the same nearly everywhere) is the PerlReTut