Extract specific text in between 2 strings - javascript

Assume we have text such as the following.
Title: (some text)
My Title [abc]
Content: (some test)
My long content paragraph. With multiple sentences. [abc]
Short Content: (some text)
Short content [abc]
Using Javascript and RegEx, is it possible to extract the text so that it would be as follows.
Title: My Title
Content: My long content paragraph. With multiple sentences.
Short Content: Short content
Basically ignoring new lines and text in the () and [] brackets?
I've tried to use Regex but I can't get it to do exactly as I'd like. I'm also getting the issue that when I match Content: i'm getting a match for both Content: & Short Content: however i'd want to only match the occurrence where it is an exact match.
EDIT:
I'm new to RegEx. So far to extract the titles such as Title:, Content: and so on I have
/[A-Za-z]+:|[A-Za-z]+ [A-Za-z]+:|[A-Za-z]+ [A-Za-z]+ [A-Za-z]+:|[A-Za-z]+ [A-Za-z]+ [0-9]+:/g
And then I loop through and use this
[TITLENAME]:.*\n.*
I'm struggling to get past this. My next step would be to loop through the text that is matched above and then remove the bracket stuff. I'm sure there is a better way to do this!

You could use String.replace( /(\(|\)|\[|\])/g , '')
If you take a string and use the replace method with these two arguments it will return a string with the ()[] characters removed. I have escaped them all with \ since they are special characters in regex. It might be a little over zealous.
Also g makes the regular expression global so it will remove all instances

If the text within parenthesis (e.g. 'abc') is fixed and have a special meaning you can also go with: '/(\(some text\)\n|\(some test\)\n|(\[abc\]))|(^$\n)/gm'.
This way you would allow parenthesis in the real text that you want to preserve, e.g. some text (this I want to preserve) and other text.
Please note the multiline m flag.
https://regex101.com/r/cS3pRR/1

Related

How to search for double spaces within <p> elements in Atom Editor?

I'm creating a web page by copy-pasting paragraphs of a Word document. When I copy-paste, the beginning of sentences is preceded by two spaces, which I'd like to replace globally by a single space. However, I would not like this to affect my indentation, which is also by two spaces.
I'm trying to do this by using Atom's 'search with regex' feature. I'm trying to enter the expression
<p>.+ .+</p>
However, this does not produce any matches:
There should be matches, though, as illustrated by the highlighted areas within the p elements in a regular search for ' ':
Also, from a little experiment in the Python shell, this regular expression seems to match what I'm looking for:
In [8]: re.findall(r'<p>.+ .+</p>', ' <p>Foo Bar</p>')
Out[8]: ['<p>Foo Bar</p>']
It seems from Atom's documentation, though, that the search term should be a Javascript RegExp expression. I tried from the docs (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) to adapt this to Javascript, but so far no success. How can I make this search in Atom work?
In the case of having <p>Foo Bar</p> as the sample input, the following find and replace will work:
"Find in current buffer" = <p>(.+) (.+)</p>
"Replace in current buffer" = <p>$1 $2</p>
The highlighted spaces in your image is within a <p class="flow-text"> - that has a class attribute - and you are searching for <p> which doesn't include attributes. You should do this:
<p[^>]*>.+ .+</p>
However this produces a single match which you have to use capturing groups to replace two spaces with one. You may want to try a more precise approach. Search for:
[ ]{2,}(?=(?:(?!<p[^>]*>).)*<\/p>)
and replace with a single space.

Match attribute value of XML string in JS

I've researched stackoverflow and find similar results but it is not really what I wanted.
Given an xml string: "<a b=\"c\"></a>" in javascript context, I want to create a regex that will capture the attribute value including the quotation marks.
NOTE: this is similar if you're using single quotation marks.
Currently I have a regular expression tailored to the XML specification:
[_A-Za-z][\w\.\-]*(?:=\"[^\"]*\")?
[_A-Za-z][\w\.\-]* //This will match the attribute name.
(?:=\"[^\"]*\")? //This will match the attribute value.
\"[^\"]*\" //This part concerns me.
My question now is, what if the xml string looks like this:
<shout statement="Hi! \"Richeve\"."></shout>
I know this is a dumb question to ask but I just want to capture rare cases that this scenario might happen (I know the coder can use single quotes on this scenario) but there are cases that we don't know the current value of the attribute given that the attribute value changes dynamically at runtime.
So to make this clearer, the result of that using the correct regex should be:
"Hi! \"Richeve\"."
I hope my question is clear. Thanks for all the help!
PS: Note that the language context is Javascript and I know it is tempting to use lookbehinds but currently lookbehinds are not supported.
PS: I know it is really hard to parse XML but I have an elegant solution to this :) so I just need this small problem to be solved. So this problem only main focus is capturing quotation marked string tokens containing quotation marks inside the string token.
The standard pattern for content with matching delimiters and embedded escaped delimiters goes like this:
"[^"\\]*(?:\\.[^"\\]*)*"
Ignoring the obvious first and last characters in the pattern, here's how the rest of the pattern works:
[^"\\]*: Consume all characters until a delimiter OR backslash (matching Hi! in your example)
(?:\\.[^"\\]*)* Try to consume a single escaped character \\. followed by a series of non delimiter/backslash characters, repeatedly (matching \"Richeve first and then \". next in your example)
That's it.
You can try to use a more generic delimiter approach using (['"]) and back references, or you can just allow for an alternate pattern with single quotes like so:
("[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*')
Here's another description of this technique that might also help (see the section called Strings): http://www.regular-expressions.info/examplesprogrammer.html
Description
I'm pretty really sure embedding double quotes inside a double quoted attribute value is not legal. You could use the unicode equivalent of a double quote \x22 inside the value.
However to answer the question, this expression will:
allow escaped quotes inside attribute values
capture the attribute statement 's value
allow attributes to appear in any order inside the tag
will avoid many of the edge cases which will trip up pattern matching inside html text
doesn't use lookbehinds
<shout\b(?=\s)(?=(?:[^>=]|='(?:[^']|\\')*'|="(?:[^"]|\\")*"|=[^'"][^\s>]*)*?\sstatement=(['"])((?:\\['"]|.)*?)\1(?:\s|\/>|>))(?:[^>=]|='(?:[^']|\\')*'|="(?:[^"]|\\")*"|=[^'"][^\s>]*)*>.*?<\/shout>
Example
Pretty Rubular
Ugly RegexPlanet set to Javascript
Sample Text
Note the difficult edge case in the first attribute :)
<shout onmouseover=' statement="He said \"I am Inside the onMouseOver\" " ; if ( 6 > a ) { funRotate(statement) } ; ' statement="Hi! \"Richeve\"." title="sometitle">SomeString</shout>
Matches
Group 0 gets the entire tag from open to close
Group 1 gets the quote surrounding the statement attribute value, this is used to match the closing quote correctly
Group 2 gets the statement attribute value which may include escaped quotes like \" but not including the surrounding quotes
[0][0] = <shout onmouseover=' statement="He said \"I am Inside the onMouseOver\" " ; if ( 6 > a ) { funRotate(statement) } ; ' statement="Hi! \"Richeve\"." title="sometitle">SomeString</shout>
[0][1] = "
[0][2] = Hi! \"Richeve\".

Remove a long dash from a string in JavaScript?

I've come across an error in my web app that I'm not sure how to fix.
Text boxes are sending me the long dash as part of their content (you know, the special long dash that MS Word automatically inserts sometimes). However, I can't find a way to replace it; since if I try to copy that character and put it into a JavaScript str.replace statement, it doesn't render right and it breaks the script.
How can I fix this?
The specific character that's killing it is —.
Also, if it helps, I'm passing the value as a GET parameter, and then encoding it in XML and sending it to a server.
This code might help:
text = text.replace(/\u2013|\u2014/g, "-");
It replaces all – (–) and — (—) symbols with simple dashes (-).
DEMO: http://jsfiddle.net/F953H/
That character is call an Em Dash. You can replace it like so:
str.replace('\u2014', '');​​​​​​​​​​
Here is an example Fiddle: http://jsfiddle.net/x67Ph/
The \u2014 is called a unicode escape sequence. These allow to to specify a unicode character by its code. 2014 happens to be the Em Dash.
There are three unicode long-ish dashes you need to worry about: http://en.wikipedia.org/wiki/Dash
You can replace unicode characters directly by using the unicode escape:
'—my string'.replace( /[\u2012\u2013\u2014\u2015]/g, '' )
There may be more characters behaving like this, and you may want to reuse them in html later. A more generic way to to deal with it could be to replace all 'extended characters' with their html encoded equivalent. You could do that Like this:
[yourstring].replace(/[\u0080-\uC350]/g,
function(a) {
return '&#'+a.charCodeAt(0)+';';
}
);
With the ECMAScript 2018 standard, JavaScript RegExp now supports Unicode property (or, category) classes. One of them, \p{Dash}, matches any Unicode character points that are dashes:
/\p{Dash}/gu
In ES5, the equivalent expression is:
/[-\u058A\u05BE\u1400\u1806\u2010-\u2015\u2053\u207B\u208B\u2212\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u2E5D\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]|\uD803\uDEAD/g
See the Unicode Utilities reference.
Here are some JavaScript examples:
const text = "Dashes: \uFF0D\uFE63\u058A\u1400\u1806\u2010-\u2013\uFE32\u2014\uFE58\uFE31\u2015\u2E3A\u2E3B\u2053\u2E17\u2E40\u2E5D\u301C\u30A0\u2E1A\u05BE\u2212\u207B\u208B\u3030𐺭";
const es5_dash_regex = /[-\u058A\u05BE\u1400\u1806\u2010-\u2015\u2053\u207B\u208B\u2212\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u2E5D\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]|\uD803\uDEAD/g;
console.log(text.replace(es5_dash_regex, '-')); // Normalize each dash to ASCII hyphen
// => Dashes: ----------------------------
To match one or more dashes and replace with a single char (or remove in one go):
/\p{Dash}+/gu
/(?:[-\u058A\u05BE\u1400\u1806\u2010-\u2015\u2053\u207B\u208B\u2212\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u2E5D\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]|\uD803\uDEAD)+/g

Regex to match all instances not inside quotes

From this q/a, I deduced that matching all instances of a given regex not inside quotes, is impossible. That is, it can't match escaped quotes (ex: "this whole \"match\" should be taken"). If there is a way to do it that I don't know about, that would solve my problem.
If not, however, I'd like to know if there is any efficient alternative that could be used in JavaScript. I've thought about it a bit, but can't come with any elegant solutions that would work in most, if not all, cases.
Specifically, I just need the alternative to work with .split() and .replace() methods, but if it could be more generalized, that would be the best.
For Example:
An input string of: +bar+baz"not+or\"+or+\"this+"foo+bar+
replacing + with #, not inside quotes, would return: #bar#baz"not+or\"+or+\"this+"foo#bar#
Actually, you can match all instances of a regex not inside quotes for any string, where each opening quote is closed again. Say, as in you example above, you want to match \+.
The key observation here is, that a word is outside quotes if there are an even number of quotes following it. This can be modeled as a look-ahead assertion:
\+(?=([^"]*"[^"]*")*[^"]*$)
Now, you'd like to not count escaped quotes. This gets a little more complicated. Instead of [^"]* , which advanced to the next quote, you need to consider backslashes as well and use [^"\\]*. After you arrive at either a backslash or a quote, you need to ignore the next character if you encounter a backslash, or else advance to the next unescaped quote. That looks like (\\.|"([^"\\]*\\.)*[^"\\]*"). Combined, you arrive at
\+(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)
I admit it is a little cryptic. =)
Azmisov, resurrecting this question because you said you were looking for any efficient alternative that could be used in JavaScript and any elegant solutions that would work in most, if not all, cases.
There happens to be a simple, general solution that wasn't mentioned.
Compared with alternatives, the regex for this solution is amazingly simple:
"[^"]+"|(\+)
The idea is that we match but ignore anything within quotes to neutralize that content (on the left side of the alternation). On the right side, we capture all the + that were not neutralized into Group 1, and the replace function examines Group 1. Here is full working code:
<script>
var subject = '+bar+baz"not+these+"foo+bar+';
var regex = /"[^"]+"|(\+)/g;
replaced = subject.replace(regex, function(m, group1) {
if (!group1) return m;
else return "#";
});
document.write(replaced);
Online demo
You can use the same principle to match or split. See the question and article in the reference, which will also point you code samples.
Hope this gives you a different idea of a very general way to do this. :)
What about Empty Strings?
The above is a general answer to showcase the technique. It can be tweaked depending on your exact needs. If you worry that your text might contain empty strings, just change the quantifier inside the string-capture expression from + to *:
"[^"]*"|(\+)
See demo.
What about Escaped Quotes?
Again, the above is a general answer to showcase the technique. Not only can the "ignore this match" regex can be refined to your needs, you can add multiple expressions to ignore. For instance, if you want to make sure escaped quotes are adequately ignored, you can start by adding an alternation \\"| in front of the other two in order to match (and ignore) straggling escaped double quotes.
Next, within the section "[^"]*" that captures the content of double-quoted strings, you can add an alternation to ensure escaped double quotes are matched before their " has a chance to turn into a closing sentinel, turning it into "(?:\\"|[^"])*"
The resulting expression has three branches:
\\" to match and ignore
"(?:\\"|[^"])*" to match and ignore
(\+) to match, capture and handle
Note that in other regex flavors, we could do this job more easily with lookbehind, but JS doesn't support it.
The full regex becomes:
\\"|"(?:\\"|[^"])*"|(\+)
See regex demo and full script.
Reference
How to match pattern except in situations s1, s2, s3
How to match a pattern unless...
You can do it in three steps.
Use a regex global replace to extract all string body contents into a side-table.
Do your comma translation
Use a regex global replace to swap the string bodies back
Code below
// Step 1
var sideTable = [];
myString = myString.replace(
/"(?:[^"\\]|\\.)*"/g,
function (_) {
var index = sideTable.length;
sideTable[index] = _;
return '"' + index + '"';
});
// Step 2, replace commas with newlines
myString = myString.replace(/,/g, "\n");
// Step 3, swap the string bodies back
myString = myString.replace(/"(\d+)"/g,
function (_, index) {
return sideTable[index];
});
If you run that after setting
myString = '{:a "ab,cd, efg", :b "ab,def, egf,", :c "Conjecture"}';
you should get
{:a "ab,cd, efg"
:b "ab,def, egf,"
:c "Conjecture"}
It works, because after step 1,
myString = '{:a "0", :b "1", :c "2"}'
sideTable = ["ab,cd, efg", "ab,def, egf,", "Conjecture"];
so the only commas in myString are outside strings. Step 2, then turns commas into newlines:
myString = '{:a "0"\n :b "1"\n :c "2"}'
Finally we replace the strings that only contain numbers with their original content.
Although the answer by zx81 seems to be the best performing and clean one, it needes these fixes to correctly catch the escaped quotes:
var subject = '+bar+baz"not+or\\"+or+\\"this+"foo+bar+';
and
var regex = /"(?:[^"\\]|\\.)*"|(\+)/g;
Also the already mentioned "group1 === undefined" or "!group1".
Especially 2. seems important to actually take everything asked in the original question into account.
It should be mentioned though that this method implicitly requires the string to not have escaped quotes outside of unescaped quote pairs.

JavaScript regex: Not starting with

I want to replace all the occurrences of a string that doesn't start with "<pre>" and doesn't end in "</pre>".
So let's say I wanted to find new-line characters and replace them with "<p/>". I can get the "not followed by" part:
var revisedHtml = html.replace(/[\n](?![<][/]pre[>])/g, "<p/>");
But I don't know the "not starting with" part to put at the front.
Any help please? :)
Here's how Steve Levithan's first lookbehind-alternative can be applied to your problem:
var output = s.replace(/(<pre>[\s\S]*?<\/pre>)|\n/g, function($0, $1){
return $1 ? $1 : '<p/>';
});
When it reaches a <pre> element, it captures the whole thing and plugs it right back into the output. It never really sees the newlines inside the element, just gobbles them up along with all other content. Thus, when the \n in the regex does match a newline, you know it's not inside a <pre> element, and should be replaced with a <p/>.
But don't make the mistake of regarding this technique as a hack or a workaround; I would recommend this approach even if lookbehinds were available. With the lookaround approach, the regex has to examine every single newline and apply the lookarounds each time to see if it should be replaced. That's a lot of unnecessary work it has to do, plus the regex is a lot more complicated and less maintainable.
As always when using regexes on HTML, I'm ignoring a lot of factors that can affect the result, like SGML comments, CDATA sections, angle brackets in attribute values, etc. You'll have to determine which among those factors you have to deal with in your case, and which ones you can ignore. When it comes to processing HTML with regexes, there's no such thing as a general solution.
Why not do the reverse. Look for all the substrings enclosed in <pre> tags. Then you know which parts of your string are not enclosed in <pre>.
EDIT: More elegant solution: use split() and use the <pre> HTML as the delimiters. This gives you the HTML outside the <pre> blocks.
var s = "blah blah<pre>formatted</pre>blah blah<pre>another formatted</pre>end";
var rgx = /<pre>.*?<\/pre>/g
var nonPreStrings = s.split(rgx);
for (var idx in nonPreStrings)
alert(nonPreStrings[idx]);

Categories

Resources