Regex to replace repeated characters - java

Can someone give me a Java regex to replace the following.
If I have a word like this "Cooooool", I need to convert this to "Coool" with 3 o's. So that I can distinguish it with the normal word "cool".
Another ex: "happyyyyyy" should be "happyyy"
replaceAll("(.)\\1+","$1"))
I tried this but it removes all the repeating characters leaving only one.

Change your regex like below.
string.replaceAll("((.)\\2{2})\\2+","$1");
( start of the first caturing group.
(.) captures any character. For this case, you may use [a-z]
\\2 refers the second capturing group. \\2{2} which must be repeated exactly two times.
) End of first capturing group. So this would capture the first three repeating characters.
\\2+ repeats the second group one or more times.
DEMO

I think you might want something like this:
str.replaceAll("([a-zA-Z])\\1\\1+", "$1$1$1");
This will match where a character is repeated 3 or more times and will replace it with the same character, three times.
$1 only matches one character, because you're surrounding the character to match.
\\1\\1+ matches the character only, if it occurs at least three times in a row.
This call is also a lot more readable, than having a huge regex and only using one $1.

Related

Regular expression for the name

I need to build a regex for a name with the following pattern, so
John D.E. would pass the regex test.
Basically what I want is:
N number of chars(a-zA-Z) goes first
Then there's exactly one space
Exactly one char(a-zA-Z)
Exactly one dot
Exactly one char(a-zA-Z)
Exactly one dot
I wrote this regex ^([a-zA-Z]*)+( {1})+([a-zA-Z]{1})+(\.)+([a-zA-Z]{1})+(\.), but it doesn't seem to work properly (the expression still allows n number of spaces, for example). How do I restrict it? {1} doesn't work.
Try this:
^([a-zA-Z])+([ ]{1})([a-zA-Z]{1})([.])([a-zA-Z]{1})([.])
I've taken space and dots into class ([]). If you don't do this with dot, then it means any character. Alo pluses are redundant, they mean more than one character.
P.S.: #f1sh correctly notices, that having {1} doesn't change a thing, so the shorter form would be:
^([a-zA-Z])+([ ])([a-zA-Z])([.])([a-zA-Z])([.])

Regular expressions - capturing groups confusion

I am reading an Oracle tutorial on regular expressions. I am on the topic Capturing groups. Though the reference is excellent, but except that a parenthesis represents a group, I am finding many difficulties in understanding the topic. Here are my confusions.
What is the significance of counting groups in an expression?
What are non-capturing groups?
Elaborating with examples would be nice.
One usually doesn't count groups other than to know which group has which number. E.g. ([abc])([def](\d+)) has three groups, so I know to refer to them as \1, \2 and \3. Note that group 3 is inside 2. They are numbered from the left by where they begin.
When searching with regex to find something in a string, as opposed to matching when you make sure the whole string matches the subject, group 0 will give you just the matched string, but not the stuff that was before or after it. Imagine if you will a pair of brackets around your whole regex. It's not part of the total count because it's not really considered a group.
Groups can be used for other things than capturing. E.g. (foo|bar) will match "foo" or "bar". If you're not interested in the contents of a group, you can make it non-capturing (e.g: (?:foo|bar) (varies by dialect)), so as not to "use up" the numbers assigned to groups. But you don't have to, it's just convenient sometimes.
Say I want to find a word that begins and ends in the same letter: \b([a-z])[a-z]*\1\b The \1 will then be the same as whatever the first group captured. Of course it can be used for much more powerful stuff, but I think you'll get the idea.
(Coming up with relevant examples is certainly the hardest part.)
Edit: I answered when the questions were:
What is the significance of counting groups in an expression?
There is a special group, called as group-0, which means the entire expression. It is not reported by groupCount() method. Why is that?
I don't understand what are non-capturing groups?
Why we need back-references? What is the significance of back-references?
Say you have a string, abcabc, and you want to figure out whether the first part of the string matches the second part. You can do this with a single regex by using capturing groups and backreferences. Here is the regex I would use:
(.+)\1
The way this works is .+ matches any sequence of characters. Because it is in parentheses, it is caught in a group. \1 is a backreference to the 1st capturing group, so it is the equivalent of the text caught by the capturing group. After a bit of backtracking, the capturing group matches the first part of the string, abc. The backreference \1 is now the equivalent of abc, so it matches the second half of the string. The entire string is now matched, so it is confirmed that the first half of the string matches the second half.
Another use of backreferences is in replacing. Say you want to replace all {...} with [...], if the text inside { and } is only digits. You can easily do this with capturing groups and backreferences, using the regex
{(\d+)}
And replacing with that with [\1].
The regex matches {123} in the string abc {123} 456, and captures 123 in the first capturing group. The backreference \1 is now the equivalent of 123, so replacing {(\d+)} in abc {123} 456 with [\1] results in abc [123] 456.
The reason non-capturing groups exist is because groups in general have more uses that just capturing. The regex (xyz)+ matches a string that consists entirely of the group, xyz, repeated, such as xyzxyzxyz. A group is needed because xyz+ only matches xy and then z repeated, i.e. xyzzzzz. The problem with using capturing groups is that they are slightly less efficient compared to non-capturing groups, and they take up an index. If you have a complicated regex with a lot of groups in it, but you only need to reference a single one somewhere in the middle, it's a lot better to just reference \1 rather than trying to count all the groups up to the one you want.
I hope this helps!
Can't think of an appropriate example at the moment, but I'm assuming someone might need to know the number of sub matches in the RegEx.
Group 0 is always the entire base match. I'm assuming groupCount() just lets you know how many capture groups you've specified in the expression.
A non-capturing group (?:) would be used to, well, not capture a group. Ex. if you need to test if a string contains one of several words and don't want to capture the word in a new group: (?:hello|hi there) world !== hello|hi there world. The first matches "hello world" or "hi there world" but the second matches "hello" or "hi there world".
They can be used as a part of a multitude of powerful reasons, such as testing whether or not a number is prime or composite. :) Or you could simply test to ensure a search parameter isn't repeated, ie. ^(\d)(?!.*\1)\d+$ would ensure the first digit is unique in a string.

Java/Hive regex interpretation

Straightforward question, it's just difficult to google regex syntax...
I'm going through the HortonWorks Hive tutorials (Hive uses same regex as Java), and the following SELECT statement uses regex to pull from what's probably JSON data...
INSERT OVERWRITE TABLE batting
SELECT
regexp_extract(col_value,'^(?:([^,]*)\.?){1}',1) player_id,
regexp_extract(col_value,'^(?:([^,]*)\.?){2}',1) year,
regexp_extract(col_value,'^(?:([^,]*)\.?){9}',1) run
FROM temp_batting;
The data looks like this:
PlayerID,yearID,stint,teamID,lgID,G,G_batting,AB,R,H,2B,3B,HR,RBI,SB,CS,BB,SO,IBB,HBP,SH,SF,GIDP,G_old
aardsda01,2004,1,SFN,NL,11,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11
aardsda01,2006,1,CHN,NL,45,43,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,45
aardsda01,2007,1,CHA,AL,25,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2
And so PlayerID is in column1, year is column2, R (runs) is column 9. How is regexp_extract successfully pulling this data?
I'm new to non-capturing groups, but it looks to me like the entire thing is a non-capturing group. Also, I'm used to seeing {1}, {2}, or {9} in the form [0-9]{9} meaning it matches a 9-digit number. In this case it looks like it's pointing to the 9th match of something, what is this syntax called?
First break apart the regex:
^(?:([^,]*)\.?){n}
^ is the start of a String
(?:...){n} is a non-capturing group repeated n times
([^,]*) is a negated character class, it matches "not ," zero or more times
\.? is an optional (literal) .
So, how does this work?
The non-capturing group is solely there for the numeric quantifier, i.e. it makes the entire pattern in the group repeat n times.
The actual pattern being captured is in the capturing group ([^,]*). I'm not sure why the optional . is there and I don't see any inputs ending with a . in your sample data but I assume there are some.
What happens is the the group is captured n times but only the last capture is stored and this is stored in the first group, i.e. group 1. This is the default in the regexp_extract.
So when the pattern repeats once in the first case we capture the first element on the comma separated array. When the pattern repeats twice in the second example we capture the second element. When the pattern repeats nine times then the ninth element is captured.
The pattern itself is actually pretty horrible as it allows for a zero length pattern to be repeated, this means that the regex engine can backtrack a lot if there is a non-matching pattern. I imagine this isn't an issue for you but it is generally bad practice.
It would be best to either make the [^,]* possessive by adding a +:
^(?:([^,]*+)\.?){n}
Or make the entire non-capturing group atomic:
^(?>([^,]*)\.?){n}
I believe that a good way to practice and learn regex is on this site: http://www.regexr.com/
Just paste your expression on there, and delete/replace parts of it. It'll all make a bit more sense than trying to decipher a regex by sight.
Another way to do this without using regex is to use split function
select split('aardsda01,2006,1,CHN,NL,45,43,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,45',',')[0] as player_id,
split('aardsda01,2006,1,CHN,NL,45,43,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,45',',')[1] as year,
split('aardsda01,2006,1,CHN,NL,45,43,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,45',',')[1] as runs

Should capturing parentheses affect a separate negative lookahead?

I am using Java. I have the following text:
"hyst and hy"
Why (hy)(?![a-z]) returns two "hy"s. The idea is to match any "hy" that is not followed by any character between a-z.
If I do hy(?![a-z]) (hy without parentheses) it works (finds only the second "hy") but I don't understand why if I use parentheses (hy) in the RegEx it matches the first "hy" in hyst
When you use a capture group you obtain two results, the first is the whole pattern and the second the capture group. The first hy has never been matched.
If you remove the parenthesis, you obtain only that match the whole pattern.

Regular expression to match simple "id" values?

I need regex for a line that starts with two characters followed by 2-4 digits or 2-4 digits followed by "-" and followed by 2-4 digits.
Examples:
AB125
AC123-25
BT1-2535
Seems simple , but I got stuck with it ...
Regular expressions always seem simple, right up to the point where you try to use them :-)
This particular one can be done with something along the lines of:
^[A-Z]{2}([0-9]{2,4}-)?[0-9]{2,4}$
That's:
2 alpha (uppercase) characters.
an optional 2-to-4-digit and hyphen sequence.
a mandatory 2-to-4-digit sequence.
start and end markers.
That last one, BT1-2535, doesn't match your textual specification by the way since it only has one digit before the hyphen. I'm assuming that was a typo. You will also have to change the character bit to use [A-Za-z] if you want to allow lowercase as well.
How about:
^[A-Z]{2}\d{2,4}(?:-\d{2,4})?
This matches two uppercase letters followed by 2-4 digits, followed by (optionally) a hyphen and another 2-4 digits.

Categories

Resources