I am trying to create a regular expression for the string filtering. I want to get the symbol "#" and anything that is written after that and before a space.
Can someone help me with this?
For example:
hi I am #vaibhav .
The expected result this regular expression should give is vaibhav.
I made this:
/#[a-z]*/
However, I am not sure if this will confirm to the above mentioned criteria.
To get a substring from the # up to the first space after it, use
#\S+
See demo
The \S means a non-whitespace character.
If you do not need #, use a capturing group:
#(\S+)
The value you need will be in Group 1. See another demo.
If you are using JavaScript:
var re = /#(\S+)/g;
var str = 'hi I am #vaibhav . hi, and I am #strib .';
var m;
while ((m = re.exec(str)) !== null) {
document.write("The value is: <b>" + m[1] + "</b><br/>");
}
The simplest solution is to use a negated set.
Search characters that are not '#'
Read in the '#'
Now capture characters that are not ' '
If you're trying to match and capture you can accomplish that like this:
[^#]*#([^ ]*).*
[Live Example]
If you only want to search then you don't need to match the whole string and you can just extract the actual match section:
#([^ ]*)
[Live Example]
The most complicated situation is where you need to deal with an escaped '#'. Here's an example of a match using that:
(?:[^\\#]|\\.)*#([^ ]*).*
[Live Example]
You can do that with lookarounds.
Edited version:
(?<=#)\w+
Demo on regex101
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 am trying to fix this since yesterday and believe I am missing something very simple.
I wrote a regex to match ANY ONE of the three IP address format:
Pattern to match : X.X.X.X OR X.X.X.X/X.X.X.X OR X.X.X.X-X.X.X.X
Regex:
/^(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\/([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))|(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\-([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))|(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))$/
Problem:
The regex matches the above 3 formats but the problem is with the alternation symbol - the behaviour is like the regex stops once the match is found.
Example: 1.1.1.1/1.1.1.1 - Once this match is found it does not check after that.
i.e: 1.1.1.1/1.1.1.1 - Valid
But 1.1.1.1/1.1.1.1(...anything after this is also recognized as valid which should not be the case...)
Question:
How do I make it to match only one of the 3 alternatives as it is. I tried a bit with word boundaries (\b) as well, but I am not sure if that is what is needed.
Any help appreciated.
Try this regex:
(^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)|(^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[\/-](?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)
You can test it using the following link for verification.
https://regex101.com/r/fC6uS3/1
The problem is that alternation has the lowest precedence of all the regex constructs. Your regex matches either:
^X.X.X.X/X.X.X.X // anchored at start only
or
X.X.X.X-X.X.X.X // not anchored
or
X.X.X.X$ // anchored at end only
You can fix it by adding another set of parentheses around everything but the anchors:
^(your regex)$
Im not sure if you want to match more than one, but if that is the case then remove "^" from the beginning and "$" from the end and also make it globally search like this:
/(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\/([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))|(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\-([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))|(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))/g
Hope this helps
You can probably shorten your regex to:
^(((([0-2][0-5][0-6])|(\d{1,2}))\.){3}((([0-2][0-5][0-6])|(\d{1,2}))))([/-](((([0-2][0-5][0-6])|(\d{1,2}))\.){3}(([0-2][0-5][0-6])|(\d{1,2}))))*$
If you are running it with javascript you would surround with /.../
var pattern = new RegExp(/^(((([0-2][0-5][0-6])|(\d{1,2}))\.){3}((([0-2][0-5][0-6])|(\d{1,2}))))([/-](((([0-2][0-5][0-6])|(\d{1,2}))\.){3}(([0-2][0-5][0-6])|(\d{1,2}))))*$/);
var testCases = {};
//should work
testCases['testCaseA'] = '1.2.3.4';
testCases['testCaseB'] = '1.2.3.4/1.256.3.4';
testCases['testCaseC'] = '1.2.3.4-1.2.3.4';
//should not work
testCases['testCaseD'] = '1.257.3.4';
testCases['testCaseE'] = '1.2.3.4/1.2.3.356';
testCases['testCaseF'] = '1.2.3.4-1.2.3.4I';
var results = '<table><tr><th>Cases</th><th>Inputs</th><th>Outputs</th></tr>';
$.each(testCases, function(k, v) {
results += '<tr><td>' + k + ' </td><td>' + v + ' </td><td>' + pattern.test(v) + '</td>';
});
document.write(results + '</table>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm working with RegEx on Javascript and here is where I stuck.
I have a simple string like
<html><body><span style=3D"font-family:Verdana; color:#000; font-size:10pt;=
"><div><font face=3D"verdana, geneva" size=3D"2">http://72.55.146.142:8880/=
order003.png.zip,120</body></html>
all i need to do is write javascript which can replace all strings in with "<" and ">" symbol.
I wrote something like this -
var strReplaceAll = Body;
var intIndexOfMatch = strReplaceAll.indexOf( "<" );
while (intIndexOfMatch != -1){
strReplaceAll = strReplaceAll.replace(/<.*>/,'')
intIndexOfMatch = strReplaceAll.indexOf( "<" );
}
but the problem is if body contains -
test<abc>test2<adg>
it will give me -
test
only or if body contains like -
<html>test<abc>test2<adg>
it will give me nothing please let me know how i can get-
testtest2
as a final output.
Try this regex instead:
<[^>]+>
DEMO:
http://regex101.com/r/kI5cJ7/2
DISCUSSION
Put the html code in a string and apply to this string the regex.
var htmlCode = ...;
htmlCode = htmlCode.replace(/<[^>]+>/g, '');
The original regex take too much characters (* is a greedy operator).
Check this page about Repetition with Star and Plus, especially the part on "Watch Out for The Greediness!".
Most people new to regular expressions will attempt to use <.+>. They will be surprised when they test it on a string like This is a <EM>first</EM> test. You might expect the regex to match <EM> and when continuing after that match, </EM>.
But it does not. The regex will match <EM>first</EM>. Obviously not what we wanted.
/(<.*?>)/
Just use this. Replace all the occurrences with "".
See demo.
How would I match the quotations around "text" in the string below and not around "TEST TEXT" using RegEx. I wanted just quotations only when they are by themselves. I tried a negative lookahead (for a second quote) but it still captured the second of the two quotes around TEST TEXT.
This is some "text". This is also some ""TEST TEXT""
Be aware that I need this to scale so sometimes it would be right in the middle of a string so something like this:
/(\s|\w)(\")(?!")/g (using $2...)
Would work in this example but not if the string was:
This is some^"text".This is also some ""TEST TEXT""
I just need quotation marks by themselves.
EDIT
FYI, this needs to be Javascript RegEx so lookbehind would not be an option for me for this one.
Since you have not tagged any particular flavor of regex I am takig liberty of using lookbehind also. You can use:
(?<!")"(?!")[^"]*"
RegEx Demo
Update: For working with Javascript you can use this regex:
/""[^"]*""|(")([^"]*)(")/
And use captured group # 1 for your text.
RegEx Demo
I'm not sure if I really understood well your needs. I'll post this answer to check if it helps you but I can delete it if it doesn't.
So, is this what you want using this regex:
"\w+?"
Working demo
By the way, if you just want to get the content within "..." you can use this regex:
"(\w+?)"
Working demo
You can't do this with a pure JavaScript regexp. I am going to eat my words now however, as you can use the following solution using callback parameters:
var regex = /""+|(")/g
replaced = subject.replace(regex, function($0, $1) {
if ($1 == "\"") return "-"; // What to replace to?
else return $0;
});
"This is some -text-. This is also some ""TEST TEXT"""
If you're needing the regex to split the string, then you can use the above to replace matches to something distinctive, then split by them:
var regex = /""+|(")/g
replaced = subject.replace(regex, function($0, $1) {
if ($1 == "\"") return "☺";
else return $0;
});
splits = replaced.split("☺");
["This is some ", "text", ". This is also some ""TEST TEXT"""]
Referenced by:http://www.rexegg.com/regex-best-trick.html
I'm trying to write a regex for use in javascript.
var script = "function onclick() {loadArea('areaog_og_group_og_consumedservice', '\x26roleOrd\x3d1');}";
var match = new RegExp("'[^']*(\\.[^']*)*'").exec(script);
I would like split to contain two elements:
match[0] == "'areaog_og_group_og_consumedservice'";
match[1] == "'\x26roleOrd\x3d1'";
This regex matches correctly when testing it at gskinner.com/RegExr/ but it does not work in my Javascript. This issue can be replicated by testing ir here http://www.regextester.com/.
I need the solution to work with Internet Explorer 6 and above.
Can any regex guru's help?
Judging by your regex, it looks like you're trying to match a single-quoted string that may contain escaped quotes. The correct form of that regex is:
'[^'\\]*(?:\\.[^'\\]*)*'
(If you don't need to allow for escaped quotes, /'[^']*'/ is all you need.) You also have to set the g flag if you want to get both strings. Here's the regex in its regex-literal form:
/'[^'\\]*(?:\\.[^'\\]*)*'/g
If you use the RegExp constructor instead of a regex literal, you have to double-escape the backslashes: once for the string literal and once for the regex. You also have to pass the flags (g, i, m) as a separate parameter:
var rgx = new RegExp("'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'", "g");
while (result = rgx.exec(script))
print(result[0]);
The regex you're looking for is .*?('[^']*')\s*,\s*('[^']*'). The catch here is that, as usual, match[0] is the entire matched text (this is very normal) so it's not particularly useful to you. match[1] and match[2] are the two matches you're looking for.
var script = "function onclick() {loadArea('areaog_og_group_og_consumedservice', '\x26roleOrd\x3d1');}";
var parameters = /.*?('[^']*')\s*,\s*('[^']*')/.exec(script);
alert("you've done: loadArea("+parameters[1]+", "+parameters[2]+");");
The only issue I have with this is that it's somewhat inflexible. You might want to spend a little time to match function calls with 2 or 3 parameters?
EDIT
In response to you're request, here is the regex to match 1,2,3,...,n parameters. If you notice, I used a non-capturing group (the (?: ) part) to find many instances of the comma followed by the second parameter.
/.*?('[^']*')(?:\s*,\s*('[^']*'))*/
Maybe this:
'([^']*)'\s*,\s*'([^']*)'