regex: read character behind number - javascript

i have regex code:
<script type="text/javascript">
var str = "kw-xr55und";
var patt1 = /[T|EE|EJU].*D/i;
document.write(str.match(patt1));
</script>
it can read:
str= "KD-R55UND" -> as UND
but if i type:
str= "kw-tc800h2und -> result tc-800h2und. //it makes script read T in front of 800
i want the result as UND
how to make the code just check at character behind the 800?
EDIT
After this code it can work:
<script type="text/javascript">
var str = "kw-tc800h2und";
var patt1 = /[EJTUG|]\D*D/i;
document.write(str.match(patt1));
</script>
but show next problem, i can show the result if:
str= "kw-tc800un2d"
i want result like -> UN2D

Try this:
var patt1 = /(T|EE|EJU)\D*$/i;
It will match a sequence of non-digit characters starting with T, EE or EJU, and finishing at the end of the string. If the string has to end with D as in your examples, you can add that in:
var patt1 = /(T|EE|EJU)\D*D$/i;
If you want to match it anywhere, not just at the end of the string, try this:
var patt1 = /(T|EE|EJU)\D*D/i;
EDIT: Oops! No, of course that doesn't work. I tried to guess what you meant by [T|EE|EJU], because it's a character class that matches one of the characters E, J, T, U or | (equivalent to [EJTU|]), and I was sure that couldn't be what you meant. But what the heck, try this:
var patt1 = /[EJTU|]\D*D/i;
I still don't understand what you're trying to do, but sometimes trial and error is the only way to move ahead. At least I tested it this time! :P
EDIT: Okay, so the match can contain digits, it just can't start with one. Try this:
var patt1 = /[EJTU|]\w*D/i;

For PCRE, try this:
/(?<=\d)\D*/
It uses a lookbehind to find a set of non-digit characters that comes immediately after a digit.
For Javascript, try this:
/\D+$/
It will match any characters that are not digits from the end of the text backwards.

Depending on what flavor of regex you're using, you can use a look behind assertion. It will essentially say 'match this if it's right after a number'.
In python it's like this:
(?<=\d)\D*
Oh, also, regex is case sensitive unless you set it not to be.

Try /[TEUJ]\D*\d*\D*D$/i if it can have 1 digit in it, but not 2. Getting any more specific would require additional information, such as the maximum length of the string, or what exactly differs between parsing tc800h2und and h2und.

Related

Javascript string after an expression

The expression str.substring(0, str.indexOf("begin:")).trim() gets me the string before begin: but if I want the string that comes after begin:, what do I do?
Or use the same substring function but use the length as the first parameter (factoring in the length of "begin:") and nothing for the second:
str.substring(str.indexOf("begin:")+6).trim()
As the docs for substring state: "If indexEnd is omitted, substring() extracts characters to the end of the string."
just split the string at begin: and get the next portion:
var strPortion=str.split("begin:");
var desiredString=strPortion[1].trim();
so if the string is: "Now we begin: it is better to try splitting the string";
the above code will give "it is better to try splitting the string";
Not completely sure, but try:
str.substring(str.indexOf("begin:"),str.length).trim()
I'm not sure if you want 'begin' included or discarded.
var needle = "begin:";
var haystack = "begin: This is a story all about how my life got flipped turned upside down";
var phrase = str.substring(str.indexOf(needle) + needle.length).trim();
That will give you what you are looking for. I only am posting the answer due to others comments of the ambiguity and modulation of the code. So yeah.
Check it out and change the needle if you'd like. Code example shows how to get before the needle as well. https://jsfiddle.net/jL6zxcu3/1/
var needle = "begin:"
str.substring(str.indexOf(needle)+ needle.length, str.length).trim()
Or
var needle = "begin:"
str.substring(str.indexOf(needle)+ needle.length).trim()
The second Paramter is not needed if you want search to the end of string

Need a regex that finds "string" but not "[string]"

I'm trying to build a regular expression that parses a string and skips things in brackets.
Something like
string = "A bc defg hi [hi] jkl mnop.";
The .match() should return "hi" but not [hi]. I've spent 5 hours running through RE's but I'm throwing in the towel.
Also this is for javascript or jquery if that matters.
Any help is appreciated. Also I'm working on getting my questions formatted correctly : )
EDIT:
Ok I just had a eureka moment and figured out that the original RegExp I was using actually did work. But when I was replaces the matches with the [matches] it simply replaced the first match in the string... over and over. I thought this was my regex refusing to skip the brackets but after much time of trying almost all of the solutions below, I realized that I was derping Hardcore.
When .replace was working its magic it was on the first match, so I quite simply added a space to the end of the result word as follows:
var result = string.match(regex);
var modifiedResult = '[' + result[0].toString() + ']';
string.replace(result[0].toString() + ' ', modifiedResult + ' ');
This got it to stop targeting the original word in the string and stop adding a new set of brackets to it with every match. Thank you all for your help. I am going to give answer credit to the post that prodded me in the right direction.
preprocess the target string by removing everything between brackets before trying to match your RE
string = "A bc defg hi [hi] jkl mnop."
tmpstring = string.replace(/\[.*\]/, "")
then apply your RE to tmpstring
correction: made the match for brackets eager per nhahtd comment below, and also, made the RE global
string = "A bc defg hi [hi] jkl mnop."
tmpstring = string.replace(/\[.*?\]/g, "")
You don't necessarily need regex for this. Simply use string manipulation:
var arr = string.split("[");
var final = arr[0] + arr[1].split("]")[1];
If there are multiple bracketed expressions, use a loop:
while (string.indexOf("[") != -1){
var arr = string.split("[");
string = arr[0] + arr.slice(1).join("[").split("]").slice(1).join("]");
}
Using only Regular Expressions, you can use:
hi(?!])
as an example.
Look here about negative lookahead: http://www.regular-expressions.info/lookaround.html
Unfortunately, javascript does not support negative lookbehind.
I used http://regexpal.com/ to test, abcd[hi]jkhilmnop as test data, hi(?!]) as the regex to find. It matched 'hi' without matching '[hi]'. Basically it matched the 'hi' so long as there was not a following ']' character.
This of course, can be expanded if needed. This has a benefit of not requiring any pre-processing for the string.
r"\[(.*)\]"
Just play arounds with this if you wanto to use regular expressions.
What do yo uwant to do with it? If you want to selectively replace parts like "hi" except when it's "[hi]", then I often use a system where I match what I want to avoid first and then what I want to watch; if it matches what I want to avoid then I return the match, otherwise I return the processed match.
Like this:
return string.replace(/(\[\w+\])|(\w+)/g, function(all, m1, m2) {return m1 || m2.toUpperCase()});
which, with the given string, returns:
"A BC DEFG HI [hi] JKL MNOP."
Thus: it replaces every word with uppercase (m1 is empty), except if the word is between square brackets (m1 is not empty).
This builds an array of all the strings contained in [ ]:
var regex = /\[([^\]]*)\]/;
var string = "A bc defg hi [hi] [jkl] mnop.";
var results=[], result;
while(result = regex.exec(string))
results.push(result[1]);
edit
To answer to the question, this regex returns the string less all is in [ ], and trim whitespaces:
"A bc defg [hi] mnop [jkl].".replace(/(\s{0,1})\[[^\]]*\](\s{0,1})/g,'$1')
Instead of skipping the match you can probably try something different - match everything but do not capture the string within square brackets (inclusive) with something like this:
var r = /(?:\[.*?[^\[\]]\])|(.)/g;
var result;
var str = [];
while((result = r.exec(s)) !== null){
if(result[1] !== undefined){ //true if [string] matched but not captured
str.push(result[1]);
}
}
console.log(str.join(''));
The last line will print parts of the string which do not match the [string] pattern. For example, when called with the input "A [bc] [defg] hi [hi] j[kl]u m[no]p." the code prints "A hi ju mp." with whitespaces intact.
You can try different things with this code e.g. replacing etc.

how to extract this kind of data and put them into a nice array?

I got a string like this one:
var tweet ="#fadil good:))RT #finnyajja: what a nice day RT #fadielfirsta: how are you? #finnyajja yay";
what kind of code should work to extract any words with # character and also removing any special char at the end of the words? so it would an array like this :
(#fadil, #finnyajja, #fadielfirsta, #finnyajja);
i have tried the following code :
var users = $.grep(tweet.split(" "), function(a){return /^#/.test(a)});
it returns this:
(#fadil, #finnyajja:, #fadielfirsta:, #finnyajja)
there's still colon ':' character at the end of some words. What should I do? any solution guys? Thanks
Here is code that is more straightforward than trying to use split:
var tweet_text ="#fadil good:))RT #finnyajja: what a nice day RT #fadielfirsta: how are you? #finnyajja yay";
var result = tweet_text.match(/#\w+/g);
The easiest way without changing your current code too much would be to just remove all colons prior to calling split:
var users = $.grep(tweet_text.replace(":","").split(" "), function(a){return /^#/.test(a)});
You could also write a regex to do all the work for you using match. Something like this:
var regex = /#[a-z0-9]+/gi;
var matches = tweet.match(regex);
This assumes that you only want letters and numbers, if certain other characters are allowed, this regex will need to be modified.
http://jsfiddle.net/YHM87/

getting contents of string between digits

have a regex problem :(
what i would like to do is to find out the contents between two or more numbers.
var string = "90+*-+80-+/*70"
im trying to edit the symbols in between so it only shows up the last symbol and not the ones before it. so trying to get the above variable to be turned into 90+80*70. although this is just an example i have no idea how to do this. the length of the numbers, how many "sets" of numbers and the length of the symbols in between could be anything.
many thanks,
Steve,
The trick is in matching '90+-+' and '80-+/' seperately, and selecting only the number and the last constant.
The expression for finding the a number followed by 1 or more non-numbers would be
\d+[^\d]+
To select the number and the last non-number, add parens:
(\d+)[^\d]*([^\d])
Finally add a /g to repeat the procedure for each match, and replace it with the 2 matched groups for each match:
js> '90+*-+80-+/*70'.replace(/(\d+)[^\d]*([^\d])/g, '$1$2');
90+80*70
js>
Or you can use lookahead assertion and simply remove all non-numerical characters which are not last: "90+*-+80-+/*70".replace(/[^0-9]+(?=[^0-9])/g,'');
You can use a regular expression to match the non-digits and a callback function to process the match and decide what to replace:
var test = "90+*-+80-+/*70";
var out = test.replace(/[^\d]+/g, function(str) {
return(str.substr(-1));
})
alert(out);
See it work here: http://jsfiddle.net/jfriend00/Tncya/
This works by using a regular expression to match sequences of non-digits and then replacing that sequence of non-digits with the last character in the matched sequence.
i would use this tutorial, first, then review this for javascript-specific regex questions.
This should do it -
var string = "90+*-+80-+/*70"
var result = '';
var arr = string.split(/(\d+)/)
for (i = 0; i < arr.length; i++) {
if (!isNaN(arr[i])) result = result + arr[i];
else result = result + arr[i].slice(arr[i].length - 1, arr[i].length);
}
alert(result);
Working demo - http://jsfiddle.net/ipr101/SA2pR/
Similar to #Arnout Engelen
var string = "90+*-+80-+/*70";
string = string.replace(/(\d+)[^\d]*([^\d])(?=\d+)/g, '$1$2');
This was my first thinking of how the RegEx should perform, it also looks ahead to make sure the non-digit pattern is followed by another digit, which is what the question asked for (between two numbers)
Similar to #jfriend00
var string = "90+*-+80-+/*70";
string = string.replace( /(\d+?)([^\d]+?)(?=\d+)/g
, function(){
return arguments[1] + arguments[2].substr(-1);
});
Instead of only matching on non-digits, it matches on non-digits between two numbers, which is what the question asked
Why would this be any better?
If your equation was embedded in a paragraph or string of text. Like:
This is a test where I want to clean up something like 90+*-+80-+/*70 and don't want to scrap the whole paragraph.
Result (Expected) :
This is a test where I want to clean up something like 90+80*70 and don't want to scrap the whole paragraph.
Why would this not be any better?
There is more pattern matching, which makes it theoretically slower (negligible)
It would fail if your paragraph had embedded numbers. Like:
This is a paragraph where Sally bought 4 eggs from the supermarket, but only 3 of them made it back in one piece.
Result (Unexpected):
This is a paragraph where Sally bought 4 3 of them made it back in one piece.

java script Regular Expressions patterns problem

My problem start with like-
var str='0|31|2|03|.....|4|2007'
str=str.replace(/[^|]\d*[^|]/,'5');
so the output becomes like:"0|5|2|03|....|4|2007" so it replaces 31->5
But this doesn't work for replacing other segments when i change code like this:
str=str.replace(/[^|]{2}\d*[^|]/,'6');
doesn't change 2->6.
What actually i am missing here.Any help?
I think a regular expression is a bad solution for that problem. I'd rather do something like this:
var str = '0|31|2|03|4|2007';
var segments = str.split("|");
segments[1] = "35";
segments[2] = "123";
Can't think of a good way to solve this with a regexp.
Here is a specific regex solution which replaces the number following the first | pipe symbol with the number 5:
var re = /^((?:\d+\|){1})\d+/;
return text.replace(re, '$15');
If you want to replace the digits following the third |, simply change the {1} portion of the regex to {3}
Here is a generalized function that will replace any given number slot (zero-based index), with a specified new number:
function replaceNthNumber(text, n, newnum) {
var re = new RegExp("^((?:\\d+\\|){"+ n +'})\\d+');
return text.replace(re, '$1'+ newnum);
}
Firstly, you don't have to escape | in the character set, because it doesn't have any special meaning in character sets.
Secondly, you don't put quantifiers in character sets.
And finally, to create a global matching expression, you have to use the g flag.
[^\|] means anything but a '|', so in your case it only matches a digit. So it will only match anything with 2 or more digits.
Second you should put the {2} outside of the []-brackets
I'm not sure what you want to achieve here.

Categories

Resources