Regex get each occurrence with newlines - regex

I have the regex from a sql query:
| Steven | 149203948 | Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Ut eu lacus gravida, lobortis nulla eu, fringilla erat.
Nullam vulputate vitae lacus quis sagittis.
Donec elementum nisl vitae arcu pulvinar tristique.
| Frank | 993847 |
Morbi bibendum facilisis risus.
Nullam facilisis, lectus nec adipiscing vehicula, urna nisi rhoncus urna,
at egestas purus nisl a sapien.
Suspendisse ac sapien ut eros luctus eleifend ac sit amet odio.
Etc etc
I'm trying to select the "name", "number" and the entire list of "Lorem Text" so that I can create a sql update statement for each lorem phrase by replacing a particular word with another word.
So I could do
UPDATE person p
SET p.lorem_text = '
$3 CHANGED TEXT $4'
WHERE p.name = $1 AND p.favorite_number = $2;
For all the entries I get back from my query.
The problem is the stupid newlines, I tried using
\| (\w*) \| (\d*) \| ((.|\R)*)OLD TEXT((.|\R)*)
But it only gets the first occurence and leaves the rest (| Frank | 993847 | etc) as the entire tail end of my selection.

\| (\w*) \| (\d*) \| ([^|]*)
The rest of regex is simplified

Related

How can i remove newline breaks in text, and replace them with a space?

I have an OCR text document where paragraphs have been broken into individual lines. I'd like to make them whole paragraphs on a single line again (as per the original PDF).
How can I use regex, or find and replace, to remove the line breaks between two lines of text and replace them with a space?
Eg:
Every line of text is on a newline. I'd like them to be whole paragraphs on a single line.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vehicula tellus faucibus metus consequat
scelerisque. Maecenas sit amet urna quis ipsum interdum consequat. Praesent elementum libero nec
velit suscipit placerat accumsan vitae lacus. Aliquam erat volutpat. Etiam egestas lectus sed orci
venenatis, ullamcorper gravida elit pulvinar. Pellentesque imperdiet, augue pulvinar sodales dapibus,
tortor magna rutrum nulla, vel ullamcorper mi purus a diam. Ut id odio sed arcu aliquet lobortis.
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec quam arcu, egestas feugiat eleifend blandit, vulputate non elit. Nulla a erat vel leo maximus
viverra at ac lorem. Nam non imperdiet lorem. Fusce tempor arcu massa, non commodo ligula lobortis
nec. Aliquam sit amet fringilla sapien, non euismod metus. Donec orci mi, sagittis vitae lobortis eu,
aliquet nec libero. Sed sodales magna lacus, pretium lobortis magna varius nec. Pellentesque quis
ipsum viverra orci lobortis egestas. Aliquam porttitor tincidunt ipsum, egestas placerat ante
consectetur in. Morbi porttitor lacus eu augue tincidunt, at aliquet lorem consectetur.
You might be looking for a programatic/dynamic approach for every new scan generated so I'm not sure if this answers your question, but since you have visual studio code in your tags I will answer how to do this in vscode.
Open keyboard shortcuts from File > Preferences > Keyboard shortcuts, and bind editor.action.joinLines to a shortcut of your choice like for example Ctrl + J.
Then go ahead and open the text you are looking to fix in vscode, select it and press that keybinding. You will notice everything will be in 1 line. I hope I helped!
I am using two regular expressions when removing linebreaks from OCR texts.
They can be used in the Find&Replace dialog from VS Code.
Remove linebreaks at lines ending with a hyphen: (?<=\w)- *\n *
Replace remaining linebreaks with whitespace, but keeping blank lines: (?<!\n) *\n *(?!\n).
Note that the * in the regular expression trims whitespace at the end and beginning of the lines.
There is also a Python tool based on Flair called dehyphen that does the job.
In my experience it produces useful results but may take quite long compared to replacing linebreaks with regular expressions.

Regex: find all of a given punctuation, only if key word exists

Is it possible to find all punctuation marks of a given type, only when a key phrase exists?
For example:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer pulvinar ac augue nec auctor. Vestibulum eleifend, sem non placerat porttitor, urna neque pulvinar enim, ut ullamcorper massa libero nec tellus. Sed est massa, congue eu auctor gravida, efficitur sit amet lacus. Nullam tincidunt posuere sollicitudin. Sed ac ullamcorper risus, ac cursus justo. Phasellus vehicula quam nec libero venenatis venenatis. Donec metus erat: maximus in risus eu: imperdiet: dignissim mauris. Aliquam sit amet augue vel ex tincidunt convallis. Morbi a sem neque. Nam tellus dolor, congue in mi eu, laoreet sodales lectus. Fusce sed ullamcorper purus. Nulla facilisi.
For above, as long as "neque" is in the text, I want to find all occurrences of ":"
I've tried something like this without luck:
(.*\neque\b.*)(?!^)([:])
This works well in my system
explanation
extract the given phrase and store it in a variable.
if the phrase exists find the symbol and count its occurrences.
#!/bin/bash
a="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer pulvinar ac augue nec auctor. Vestibulum eleifend, sem non placerat porttitor, urna neque pulvinar enim, ut ullamcorper massa libero nec tellus. Sed est massa, congue eu auctor gravida, efficitur sit amet lacus. Nullam tincidunt posuere sollicitudin. Sed ac ullamcorper risus, ac cursus justo. Phasellus vehicula quam nec libero venenatis venenatis. Donec metus erat: maximus in risus eu: imperdiet: dignissim mauris. Aliquam sit amet augue vel ex tincidunt convallis. Morbi a sem neque. Nam tellus dolor, congue in mi eu, laoreet sodales lectus. Fusce sed ullamcorper purus. Nulla facilisi."
b=$(echo "$a"| grep -o "neque"| head -1)
echo $b
if [ "$b" == "neque" ]
then
number_of_occurences=$(echo "$a"| grep -o ":"| wc -l)
echo "$number_of_occurences"
fi
Your desired action is not clear. What I can read from the highlights in your example, you want to find all words that end in :, but only if the word neque exists anywhere in the text. Assuming that is the case, you can use this regex:
/(?=.*\bneque\b)\w+:/g
Explanation:
(?=.*\bneque\b) - positive lookahead for neque with word boundaries, anywhere in the text; if this fails, the whole regex fails
\w+: - look for a word that is followed by :
use the g to find all occurrences of words followed by :
EDIT: After seeing that the bash tag has been added, here is a shell script version using a shortened string. The first example has the neque keyword, the second one not:
$ echo 'Urna neque metus erat: maximus in risus eu: imperdiet: dignissim.'\
> | egrep '\bneque\b' | egrep -o '\w+:'
erat:
eu:
imperdiet:
$
$ echo 'Urna metus erat: maximus in risus eu: imperdiet: dignissim.'\
> | egrep '\bneque\b' | egrep -o '\w+:'
$
Explanation:
use first egrep to filter by required keyword neque using word boundaries
use second 'egrep' with -o flag to extract words followed by :

Regular expression in reverse

In Notepad++ I want to make an expression that only keeps the email addresses of that text and that removes everything else.
Imagine that we have the following text:
Lorem ipsum dolor sit amet, <micorreo0#gmail.com>consectetur adipiscing elit. Curabitur ac risus molestie, laoreet ligula vitae, tincidunt risus.<micorreo1#gmail.com> Aliquam ut felis efficitur, iaculis nunc in, feugiat dui.<micorreo2#gmail.com> Etiam sodales ligula tellus, id vehicula augue aliquet eu. Nulla blandit maximus lectus, quis consequat metus vulputate suscipit. Duis finibus lorem justo, non sollicitudin urna aliquet a. Sed at ligula justo. Nam est ex, suscipit in facilisis nec, rutrum vitae urna<micorreo3#gmail.com>.
The mails will always go between the <> signs.
Ctrl+H
Find what: [^<]*(<[^>]+>)[^<]*
Replace with: $1
Replace all
Explanation:
[^<]* : 0 or more any character that is not <
( : begin capture group
< : literally <
[^>]+ : 1 or more any character that is not >
> : literally >
) : end group
[^<]* : 0 or more any character that is not <
Replacement:
$1 : group 1

VB.net Regular expression to return until last sentence before ellipsis or three full-stops

I am trying to write an expression to take a block of text an return up until a full-stop before an ellipsis or three full-stops (... or …). So the idea is that the example text test string:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam felis nisi, eleifend ut quam eget, venenatis vestibulum turpis. Nam dignissim laoreet iaculis. Etiam sit amet rhoncus sem. Duis laoreet justo tellus, at volutpat risus molestie sed. Etiam posuere, arcu vitae faucibus hendrerit, lorem elit consequat urna, id congue eros felis in mauris. Donec non fermentum ipsum. Curabitur nec...
Would become:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam felis nisi, eleifend ut quam eget, venenatis vestibulum turpis. Nam dignissim laoreet iaculis. Etiam sit amet rhoncus sem. Duis laoreet justo tellus, at volutpat risus molestie sed. Etiam posuere, arcu vitae faucibus hendrerit, lorem elit consequat urna, id congue eros felis in mauris. Donec non fermentum ipsum.
So far I have come up with this pathetic attempt. I keep getting right up until the last full-stop (because the quantifier consumes the previous two full-stops so there is nothing for the look ahead to fail on). I just can't seem to wrap my head around it:
Dim testText As String = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam felis nisi, eleifend ut quam eget, venenatis vestibulum turpis. Nam dignissim laoreet iaculis. Etiam sit amet rhoncus sem. Duis laoreet justo tellus, at volutpat risus molestie sed. Etiam posuere, arcu vitae faucibus hendrerit, lorem elit consequat urna, id congue eros felis in mauris. Donec non fermentum ipsum. Curabitur nec..."
Dim ellipsisExpression As String = "(.*\.(?!\.\.))"
Dim ellipsisMatch As Match
ellipsisMatch = Regex.Match(testText, ellipsisExpression)
If ellipsisMatch.Success Then
testText = ellipsisMatch.Groups(1).Value
End If
edit: I also need this expression to take any ... character in the text into account. for example the string:
`begin. this is a test... test complete. beginning shutdown... shutting down... `
should return
`begin. this is a test... test complete.`
The aim of this expression is to find the most flowing text before any truncation has occurred. A block of text with closure so it doesn't confuse readers expecting to be able to 'get more'.
You could replace [^.]*(?:\.{3}|…).* with an empty string to get the desired result.
For example:
result = Regex.Replace(input, "[^.]*(?:\\.{3}|…).*", "")
Use this:
result = Regex.Replace(input, "(.+\.).+(?:\.{3}|…)\s*", "$1")
Edit:
Use this regex instead:
(.+[^.]\.)(?:(?:[^.]{2})|$)
You could match that with:
.*(?<!\.)\.(?!\.)(?=(?:[^.]+|\.{3})*(?:\.{3}|…)$)
Or replace
(?<!\.)\.(?!\.)(?:[^.]+|\.{3})*(?:\.{3}|…)$
with a ..
I think I have come up with a solution that works for me. Thank you to everyone who answered previously but this expression seems to do what I need and doesn't execute as slowly as some of the other answers. It also takes other sentence terminating punctuation into account such as ! or ? and not just ..
(.*([^\.](?=\.|\?|!)(?!\.\.\.)).)
This get's the last sentence terminating character (defined with the lookahead). In this case they are ?, ! and . that isn't followed by .... This also solves the ellipsis character issue since it is effectively a sentence terminating white list. This expression succeeds in finding the largest block of text with closure.

how to replace dots inside quote in sentence with regex

lets say there is something like this
Lorem ipsum dolor sit amet, consectetur adipiscing elit. "Vestibulum interdum dolor nec sapien blandit a suscipit arcu fermentum. Nullam lacinia ipsum vitae enim consequat iaculis quis in augue. Phasellus fermentum congue blandit. Donec laoreet, ipsum et vestibulum vulputate, risus augue commodo nisi, vel hendrerit sem justo sed mauris." Phasellus ut nunc neque, id varius nunc. In enim lectus, blandit et dictum at, molestie in nunc. Vivamus eu ligula sed augue pretium tincidunt sit amet ac nisl. "Morbi eu elit diam, sed tristique nunc."
to be something like this
Lorem ipsum dolor sit amet, consectetur adipiscing elit. "Vestibulum interdum dolor nec sapien blandit a suscipit arcu fermentum[dot] Nullam lacinia ipsum vitae enim consequat iaculis quis in augue[dot] Phasellus fermentum congue blandit[dot] Donec laoreet, ipsum et vestibulum vulputate, risus augue commodo nisi, vel hendrerit sem justo sed mauris[dot]" Phasellus ut nunc neque, id varius nunc. In enim lectus, blandit et dictum at, molestie in nunc. Vivamus eu ligula sed augue pretium tincidunt sit amet ac nisl. "Morbi eu elit diam, sed tristique nunc[dot]"
i somehow found a regex to select all the "{sentence}" with "(.)+?" or use them like
regex('"(.)+?"','[sentence]')
but can we do something like replace the dots inside a group?. so i can get the output like above example?
I'm not sure regexps are able to suit your needs on their own.
You should implement an algorithm that replaces nested dots until the string doesn't contain nested dots anymore.
For example in PHP:
$string = 'He asked "Please." while she answered "No. Or maybe yes."';
var_dump($string);
while(preg_match('/"[^"]*\.[^"]*"/', $string)) {
$string = preg_replace('/("[^"]*)\.([^"]*")/', '$1[dot]$2', $string);
}
var_dump($string);
which prints:
string 'He asked "Please." while she answered "No. Or maybe yes."' (length=57)
string 'He asked "Please[dot]" while she answered "No[dot] Or maybe yes[dot]"' (length=69)
This is what I would do.
echo
preg_replace_callback('~(?<!\\\)"(.+?)((?<!\\\)")~',
/*
Pattern:
--------
(?<!\\\)" a double quote not preceded by a backward (escaping) slash
(.+?) anything (with min 1 char.) between condition above and below
((?<!\\\)") a double quote not preceded by a backward (escaping) slash
*/
// for anything that matches the above pattern
// the following function is called
create_function('$m',
'return preg_replace("~\.~","[dot]",$m[0]);'),
// which replaces each dot with [dot] and returns the match
$str);
EDIT: Added explanations in comments.
try this:
(\"[^\.]*)\.([^\"]*) to \1[dot]\2
works well in my editor, but sometimes $ is used instead of \ in replacement (e.g. in php)
With Javascript I would just do a basic replace:
str = str.replace(/".+?"/g,function(m) {
return m.replace(/\./g,'[dot]');
});