My string:
AA,$,DESCRIPTION(Sink, clinical),$
Wanted matches:
AA
$
DESCRIPTION(Sink, clinical)
$
My regex sofar:
\+d|[\w$:0-9`<>=&;?\|\!\#\+\%\-\s\*\(\)\.ÅÄÖåäö]+
This gives
AA
$
DESCRIPTION(Sink
clinical)
I want to keep matches between ()
https://regex101.com/r/MqFUmk/3
Here's my attempt at the regex
\+d|[\w$:0-9`<>=&;?\|\!\#\+\%\-\s\*\.ÅÄÖåäö]+(\(.+\))?
I removed the parentheses from within the [ ] characters, and allowed capture elsewhere. It seems to satisfy the regex101 link you posted.
Depending on how arbitrary your input is, this regex might not be suitable for more complex strings.
Alternatively, here's an answer which could be more robust than mine, but may only work in Ruby.
((?>[^,(]+|(\((?>[^()]+|\g<-1>)*\)))+)
That one seems to work for me?
([^,\(\)]*(?:\([^\(\)]*\))?[^,\(\)]*)(?:,|$)
https://regex101.com/r/hLyJm5/2
Hope this helps!
Personally, I would first replace all commas within parentheses () with a character that will never occur (in my case I used # since I don't see it within your inclusions) and then I would split them by commas to keep it sweet and simple.
myStr = "AA,$,DESCRIPTION(Sink, clinical),$"; //Initial string
myStr = myStr.replace(/(\([^,]+),([^\)]+\))/g, "$1#$2"); //Replace , within parentheses with #
myArr = myStr.split(',').map(function(s) { return s.replace('#', ','); }); //Split string on ,
//myArr -> ["AA","$","DESCRIPTION(Sink, clinical)","$"]
optionally, if you're using ES6, you can change that last line to:
myArr = myStr.split(',').map(s => s.replace('#', ',')); //Yay Arrow Functions!
Note: If you have nested parentheses, this answer will need a modification
At last take an aproximation of what you need:
\w+(?:\(.*\))|\w+|\$
https://regex101.com/r/MqFUmk/4
Related
I want to replace a text after a forward slash and before a end parantheses excluding the characters.
My text:
<h3>notThisText/IWantToReplaceThis)<h3>
$('h3').text($('h3').text().replace(regEx, 'textReplaced'));
Wanted result after replace:
notThisText/textReplaced)
I have tried
regex = /([^\/]+$)+/ //replaces the parantheses as well
regex = \/([^\)]+) //replaces the slash as well
but as you can see in my comments neither of these excludes both the slash and the end parantheses. Can someone help?
A pattern like /(?<=\/)[^)]+(?=\))/ won't work in JS as its regex engine does not support a lookbehind construct. So, you should use one of the following solutions:
s.replace(/(\/)[^)]+(\))/, '$1textReplaced$2')
s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')
s.replace(/(\/)[^)]+/, '$1textReplaced')
s.replace(/\/[^)]+\)/, '/textReplaced)')
The (...) forms a capturing group that can be referenced to with $ + number, a backreference, from the replacement pattern. The first solution is consuming / and ), and puts them into capturing groups. If you need to match consecutive, overlapping matches, use the second solution (s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')). If the ) is not required at the end, the third solution (replace(/(\/)[^)]+/, '$1textReplaced')) will do. The last solution (s.replace(/\/[^)]+\)/, '/textReplaced)')) will work if the / and ) are static values known beforehand.
You can use str.split('/')
var text = 'notThisText/IWantToReplaceThis';
var splited = text.split('/');
splited[1] = 'yourDesireText';
var output = splited.join('/');
console.log(output);
Try Following: In your case startChar='/', endChar = ')', origString=$('h3').text()
function customReplace(startChar, endChar, origString, replaceWith){
var strArray = origString.split(startChar);
return strArray[0] + startChar + replaceWith + endChar;
}
First of all, you didn't define clearly what is the format of the text which you want to replace and the non-replacement part. For example,
Does notThisText contain any slash /?
Does IWantToReplaceThis contain any parentheses )?
Since there are too many uncertainties, the answer here only shows up the pattern exactly matches your example:
yourText.replace(/(\/).*?(\))/g, '$1textReplaced$2')
var text = "notThisText/IWantToReplaceThis";
text = text.replace(/\/.*/, "/whatever");
output : "notThisText/whatever"`
I thought it was very simple to find out. But how many ways I tried still not work properly.
Below is the test snippet.
"100$ and 1.000,000EUR 1,00.0.000USD .90000000000000000000$ (09898)".replace(/[\.,\d]*/g, '{n}')
And I want the result like below.
{n}$ and {n}EUR {n}USD {n}$ ({n})
The * is your problem, change the regex to /[.,\d]+/g instead.
"100$ and 1.000,000EUR 1,00.0.000USD .90000000000000000000$ (09898)".replace(/[.,\d]+/g, '{n}');
Output
{n}$ and {n}EUR {n}USD {n}$ ({n})
JSFiddle Example Check console screen for the output.
The problem here is that [\.,\d]* can match an empty string. The first step would be to use [.,\d]+ so that at least one of these characters matches.
But a better regex would be \d[.,\d]* because it ensures the replaced characters begin with a digit, so it won't replace periods in sentences.
If you want to go further, you can also use (?=[.,\d]*\d)[.,\d]+ if to handle numbers starting with periods. This one would be the proper answer for your case. The lookahead ensures there's at least one digit anywhere in the replaced text.
Note that you don't need to escape the . inside a character class.
\.?\d[^\s]*\d
Try this.Replace with {n}.See demo.
http://regex101.com/r/kP8uF5/3
var re = /\.?\d[^\s]*\d/gm;
var str = '100$ and 1.000,000EUR 1,00.0.000USD .90000000000000000000$ (09898)';
var subst = '{n}';
var result = str.replace(re, subst);
I need to match the text between two brackets. many post are made about it but non are supported by JavaScript because they all use the lookbehind.
the text is as followed
"{Code} - {Description}"
I need Code and Description to be matched with out the brackets
the closest I have gotten is this
/{([\s\S]*?)(?=})/g
leaving me with "{Code" and "{Description" and I followed it with
doing a substring.
so... is there a way to do a lookbehind type of functionality in Javascript?
You could simply try the below regex,
[^}{]+(?=})
Code:
> "{Code} - {Description}".match(/[^}{}]+(?=})/g)
[ 'Code', 'Description' ]
Use it as:
input = '{Code} - {Description}';
matches = [], re = /{([\s\S]*?)(?=})/g;
while (match = re.exec(input)) matches.push(match[1]);
console.log(matches);
["Code", "Description"]
Actually, in this particular case, the solution is quite easy:
s = "{Code} - {Description}"
result = s.match(/[^{}]+(?=})/g) // ["Code", "Description"]
Have you tried something like this, which doesn't need a lookahead or lookbehind:
{([^}]*)}
You would probably need to add the global flag, but it seems to work in the regex tester.
The real problem is that you need to specify what you want to capture, which you do with capture groups in regular expressions. The part of the matched regular expression inside of parentheses will be the value returned by that capture group. So in order to omit { and } from the results, you just don't include those inside of the parentheses. It is still necessary to match them in your regular expression, however.
You can see how to get the value of capture groups in JavaScript here.
I've a string done like this: "http://something.org/dom/My_happy_dog_%28is%29cool!"
How can I remove all the initial domain, the multiple underscore and the percentage stuff?
For now I'm just doing some multiple replace, like
str = str.replace("http://something.org/dom/","");
str = str.replace("_%28"," ");
and go on, but it's really ugly.. any help?
Thanks!
EDIT:
the exact input would be "My happy dog is cool!" so I would like to get rid of the initial address and remove the underscores and percentage and put the spaces in the right place!
The problem is that trying to put a regex on Chrome "something goes wrong". Is it a problem of Chrome or my regex?
I'd suggest:
var str = "http://something.org/dom/My_happy_dog_%28is%29cool!";
str.substring(str.lastIndexOf('/')+1).replace(/(_)|(%\d{2,})/g,' ');
JS Fiddle demo.
The reason I took this approach is that RegEx is fairly expensive, and is often tricky to fine tune to the point where edge-cases become less troublesome; so I opted to use simple string manipulation to reduce the RegEx work.
Effectively the above creates a substring of the given str variable, from the index point of the lastIndexOf('/') (which does exactly what you'd expect) and adding 1 to that so the substring is from the point after the / not before it.
The regex: (_) matches the underscores, the | just serves as an or operator and the (%\d{2,}) serves to match digit characters that occur twice in succession and follow a % sign.
The parentheses surrounding each part of the regex around the |, serve to identify matching groups, which are used to identify what parts should be replaced by the ' ' (single-space) string in the second of the arguments passed to replace().
References:
lastIndexOf().
replace().
substring().
You can use unescape to decode the percentages:
str = unescape("http://something.org/dom/My_happy_dog_%28is%29cool!")
str = str.replace("http://something.org/dom/","");
Maybe you could use a regular expression to pull out what you need, rather than getting rid of what you don't want. What is it you are trying to keep?
You can also chain them together as in:
str.replace("http://something.org/dom/", "").replace("something else", "");
You haven't defined the problem very exactly. To get rid of all stretches of characters ending in %<digit><digit> you'd say
var re = /.*%\d\d/g;
var str = str.replace(re, "");
ok, if you want to replace all that stuff I think that you would need something like this:
/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g
test
var string = "http://something.org/dom/My_happy_dog_%28is%29cool!";
string = string.replace(/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g,"");
I have the following code:
var x = "100.007"
x = String(parseFloat(x).toFixed(2));
return x
=> 100.01
This works awesomely just how I want it to work. I just want a tiny addition, which is something like:
var x = "100,007"
x.replace(",", ".")
x.replace
x = String(parseFloat(x).toFixed(2));
x.replace(".", ",")
return x
=> 100,01
However, this code will replace the first occurrence of the ",", where I want to catch the last one. Any help would be appreciated.
You can do it with a regular expression:
x = x.replace(/,([^,]*)$/, ".$1");
That regular expression matches a comma followed by any amount of text not including a comma. The replacement string is just a period followed by whatever it was that came after the original last comma. Other commas preceding it in the string won't be affected.
Now, if you're really converting numbers formatted in "European style" (for lack of a better term), you're also going to need to worry about the "." characters in places where a "U.S. style" number would have commas. I think you would probably just want to get rid of them:
x = x.replace(/\./g, '');
When you use the ".replace()" function on a string, you should understand that it returns the modified string. It does not modify the original string, however, so a statement like:
x.replace(/something/, "something else");
has no effect on the value of "x".
You can use a regexp. You want to replace the last ',', so the basic idea is to replace the ',' for which there's no ',' after.
x.replace(/,([^,]*)$/, ".$1");
Will return what you want :-).
You could do it using the lastIndexOf() function to find the last occurrence of the , and replace it.
The alternative is to use a regular expression with the end of line marker:
myOldString.replace(/,([^,]*)$/, ".$1");
You can use lastIndexOf to find the last occurence of ,. Then you can use slice to put the part before and after the , together with a . inbetween.
You don't need to worry about whether or not it's the last ".", because there is only one. JavaScript doesn't store numbers internally with comma or dot-delimited sets.