Please help.
I need a regular expression (to be used in javascript) to replace "." with "#" in a text containing Unicode characters.
Replacement takes place only when "." appears between text but not between digits.
Input: "ΦΨ. ABC. DEF. 123.456"
Desired output: "ΦΨ# ABC# DEF# 123.456"
Any suggestions?
You can use capturing groups in the regex and use back-references to obtain the required result:
var re = /(\D)\.(\D)/g;
var str = 'ΦΨ. ABC. DEF. 123.456';
var subst = '$1#$2';
result = str.replace(re, subst);
alert(result);
Regex Explanation:
\D - A non-digit character
\. - A literal dot
The non-digit characters are captured into groups, and then inserted back with the help of $1 and $2 back-references.
try this:
var str = "ΦΨ. ABC. DEF. 123.456";
str.replace(/[^\d.]+\.[^\d]/g, function (m) {
return m.replace('.', '#')
});
Related
I want to replace {r-group1} with "REPLACED" but leave the , where it is.
So, the string
var string = "{r-group1, }foo bar"
should output: "REPLACED, foo bar"
Using a negative lookahead, I tried adding a preceding (?![,]) group to leave the comma alone:
var replaced = string.replace(^(?:(?![,]){r-group1\})+$, 'REPLACED');
But it returns the same string. There are no matches to replace.
The same goes for a preceding comma:
var string = "foo bar{r-, group1}"
This should output: "foo bar, REPLACED"
You could do the replacement without a lookahead. You could match the curly braces and the content that comes before and after it except a comma using a negated character class [^,}]+ and capture the comma with optional whitespace chars in a capturing group.
In the replacement use the capturing groups $1REPLACED$2
Credits to #Nick for the updated pattern.
{r-(,?\s*)[^,}]+(,?\s*)}
Regex demo
const regex = /{r-(,?\s*)[^,}]+(,?\s*)}/g;
const str = `{r-group1, }foo bar`;
const subst = `$1REPLACED$2`;
const result = str.replace(regex, subst);
console.log(result);
var str='The_Andy_Griffith_Show'; // string to perform replace on
var regExp1=/\s|[A-Z]/g;
var regExp2=/[^A-Z]/g; // regular expression
var str2 =str.replace(regExp2,regExp1);
// expected output: The_ Andy_ Griffith_ Show
I want to replace all the first capital letters of a string with a space and that same letter, and if that's not possible is there a workaround?
If you want to add a space before any captial letter, it is enough to use
var str='The_Andy_Griffith_Show';
str = str.replace(/[A-Z]/g, ' $&')
console.log(str); // => " The_ Andy_ Griffith_ Show"
Here, /[A-Z]/g matches all ASCII uppercase letters and $& is a backreference to the whole match value.
If you want to only add a space before the first capital letter in a word, you need to use capturing groups and backreferences to thier values in the replacement pattern:
var str='The_Andy_Griffith_Show'; // string to perform replace on
str = str.replace(/(^|[^A-Z])([A-Z])/g, '$1 $2')
console.log(str); // => " The_ Andy_ Griffith_ Show"
Remove ^| if you do not want to add space before a capital letter at the string start (i.e. use /([^A-Z])([A-Z])/g).
Just an alternative to the other answers.
To get that expected result you could just match the non-uppercases that are followed by an uppercase character, then replace them with the match $& and a space.
For example:
var str='The_Andy_Griffith_Show';
str = str.replace(/[^A-Z](?=[A-Z])/g, '$& ')
console.log(str);
Or simply match those uppercases followed by an uppercase character.
var str='The_Andy_Griffith_Show';
str = str.replace(/[_](?=[A-Z])/g, '$& ')
console.log(str);
To add space to all occurrences of capital letters:
var str = 'The_Andy_Griffith_Show',
str2 = str.replace(/[A-Z]/g, letter => ` ${letter}`);
console.log(str2);
Notice that if you want no to add space to the first letter occurrence, just use the regular expression /(?!^)[A-Z]/g.
The best way to explain this is by example. I'm using jQuery to do this.
Example I have a string
var str = "1.) Ben"
how can I dynamically omit the character 1.) including the space such that str === "Ben"
str can be dynamic such that order can increment from ones, tens, to hundreds.
E.G.
var str = "52.) Ken Bush"
or
var str = "182.) Hailey Quen"
Expected output
str === "Ken Bush"
or
str === "Hailey Quen"
Example
var str = "182.) Hailey Quen"
var test = str.split(') ');
test = test[1];
//output "Hailey Quen"
You can use regex replacement to get what you want.
var str = "182.) Hailey"
var newStr = str.replace(/^\d+\.\)\s*/, '')
// Hailey
var s = "1456.) Hard Spocker".replace(/^\d+\.\)\s*/, '')
// Hard Spocker
^ makes sure that the pattern is matched at the start of the string only
\d+ will match one or more digits.
\. will match the . with escaping
) is a symbol so we need to escape it using \ as \)
\s* will match one or more spaces.
You can learn about these symbols here.
Try using .substring() and .indexOf() as shown :-
var str = "182.) Hailey Quen"
alert(str.substring(str.indexOf(' ')))
DEMO
OR use .split() as shown :-
var str = "182.) Hailey Quen"
alert($.trim(str.split(')')[1]))
DEMO
You can do it regular expression,
var str = "52.) Ken".replace(/\d+\.\)\s/g,"");
console.log(str); //Ken
DEMO
If you have zero or more than zero spaces after the ) symbol then you can use *,
var str = "52.) Ken".replace(/\d+\.\)\s*/g,"");
console.log(str); //Ken
Dismantling regex used,
/ states regex left border
\d d states normal character d, if we want to make it match
numbers then we have to escape it with \
+ It states that one or more number should be there.
\. Again . is a metacharacter to match any valid character, so
escape it.
\) Parenthesis is also a metacharacter to close a group, escape
it.
\s* 12.) can be followed by zero or more spaces.
/ states regex right boundary.
g global flag, which used to do a search recursively.
You can do it like this
var testURL = "182.) Hailey Quen";
var output = testURL.substring(testURL.lastIndexOf(")") + 1).trim();
console.log(output);
*trim function will help to remove extra space if any.Hope it will help
I'm trying to match all the words starting with # and words between 2 # (see example)
var str = "#The test# rain in #SPAIN stays mainly in the #plain";
var res = str.match(/(#)[^\s]+/gi);
The result will be ["#The", "#SPAIN", "#plain"] but it should be ["#The test#", "#SPAIN", "#plain"]
Extra: would be nice if the result would be without the #.
Does anyone has a solution for this?
You can use
/#\w+(?:(?: +\w+)*#)?/g
See the demo here
The regex matches:
# - a hash symbol
\w+ - one or more alphanumeric and underscore characters
(?:(?: +\w+)*#)? - one or zero occurrence of:
(?: +\w+)* - zero or more occurrences of one or more spaces followed with one or more word characters followed with
# - a hash symbol
NOTE: If there can be characters other than word characters (those in the [A-Za-z0-9_] range), you can replace \w with [^ #]:
/#[^ #]+(?:(?: +[^ #]+)*#)?/g
See another demo
var re = /#[^ #]+(?:(?: +[^ #]+)*#)?/g;
var str = '#The test-mode# rain in #SPAIN stays mainly in the #plain #SPAIN has #the test# and more #here';
var m = str.match(re);
if (m) {
// Using ES6 Arrow functions
m = m.map(s => s.replace(/#$/g, ''));
// ES5 Equivalent
/*m = m.map(function(s) {
return s.replace(/#$/g, '');
});*/ // getting rid of the trailing #
document.body.innerHTML = "<pre>" + JSON.stringify(m, 0, 4) + "</pre>";
}
You can also try this regex.
#(?:\b[\s\S]*?\b#|\w+)
(?: opens a non capture group for alternation
\b matches a word boundary
\w matches a word character
[\s\S] matches any character
See demo at regex101 (use with g global flag)
I need your help again with a regex.
I have this string:
some string
text1
name="yyy", path="C:/asdf/qwer.jpg" type="jjj"
text2
name="3yu", path="C:/asdf/12t2.mov" type="uuu"
And I have this regex by far:
/\b(string\b(.|\n)*?)\btext1\b/
Now, I need to replace the path of text1 so the output will be:
some string
text1
name="yyy", path="D:/here/is/my/another/path.png" type="jjj"
text2
name="3yu", path="C:/asdf/12t2.mov" type="uuu"
I know that I need to use this also (lmk if I wrong, also what is better to use?):
/".*?"/
or:
/"[^"]*"/
But how do I tell it to replace like I need?
You can replace that string this way:
var re = /(string[\s\S]*?text1[\s\S]*?\bpath=")[^"]+/;
var str = 'some string\n\ntext1\n\nname="yyy", path="C:/asdf/qwer.jpg" type="jjj"\n\ntext2\n\nname="3yu", path="C:/asdf/12t2.mov" type="uuu"';
var subst = '$1D:/here/is/my/another/path.png';
document.write(str.replace(re, subst).replace(/\n/g,"<br/>"));
The regex is
/(string[\s\S]*?text1[\s\S]*?\bpath=")[^"]+/
EXPLANATION:
(string[\s\S]*?text1[\s\S]*?\bpath=") - a capturing group that will capture the text into group 1 that we'll refer to later usign a $1 backreference in the replacement string. It matches:
string - literal string
[\s\S]*? - any 0 or more characters, as few as possible
text1 - text1 literally
[\s\S]*? - any 0 or more characters, as few as possible
\bpath=" - matches path=" literally with a non-word character (e.g. space) before path (you may remove it if it is part of a longer word)
[^"]+ - 1 or more characters other than ".
(\bstring\b[\s\S]*?\btext1\b(?:(?!\btext\d+\b)[\s\S])*path=")[^"]*
You can use this.Replace by $1mypath.See demo.
https://regex101.com/r/fX3oF6/3
var re = /(\bstring\b[\s\S]*?\btext1\b(?:(?!\btext\d+\b)[\s\S])*path=")[^"]*/g;
var str = 'some string\n\n text1\n\n name="yyy", path="C:/asdf/qwer.jpg" type="jjj"\n\n text2\n\n name="3yu", path="C:/asdf/12t2.mov" type="uuu"\n';
var subst = ' $1mypath';
var result = str.replace(re, subst);