I am trying to select just what comes after name= and before the & in :
"/pages/new?name=J&return_url=/page/new"
So far I have..
^name=(.*?).
I am trying to return in this case, just the J, but its dynamic so it could very several characters, letters, or numbers.
The end case situation would be allowing myself to do a replace statement on this dynamic variable found by regex.
/name=([^&]*)/
remove the ^ and end with an &
Example:
var str = "/pages/new?name=J&return_url=/page/new";
var matches = str.match(/name=([^&]*)/);
alert(matches[1]);
The better way is to break all the params down (Example using current address):
function getParams (str) {
var queryString = str || window.location.search || '';
var keyValPairs = [];
var params = {};
queryString = queryString.replace(/.*?\?/,"");
if (queryString.length)
{
keyValPairs = queryString.split('&');
for (pairNum in keyValPairs)
{
var key = keyValPairs[pairNum].split('=')[0];
if (!key.length) continue;
if (typeof params[key] === 'undefined')
params[key] = [];
params[key].push(keyValPairs[pairNum].split('=')[1]);
}
}
return params;
}
var url = "/pages/new?name=L&return_url=/page/new";
var params = getParams(url);
params['name'];
Update
Though still not supported in any version of IE, URLSearchParams provides a native way of retrieving values for other browsers.
The accepted answer includes the hash part if there is a hash right after the params. As #bishoy has in his function, the correct regex would be
/name=([^&#]*)/
Improving on previous answers:
/**
*
* #param {string} name
* #returns {string|null}
*/
function getQueryParam(name) {
var q = window.location.search.match(new RegExp('[?&]' + name + '=([^&#]*)'));
return q && q[1];
}
getQueryParam('a'); // returns '1' on page http://domain.com/page.html?a=1&b=2
here is the full function (tested and fixed for upper/lower case)
function getParameterByName (name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name.toLowerCase() + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search.toLowerCase());
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
The following should work:
\?name=(.*?)&
var myname = str.match(/\?name=([^&]+)&/)[1];
The [1] is because you apparently want the value of the group (the part of the regex in brackets).
var str = "/pages/new?name=reaojr&return_url=/page/new";
var matchobj = str.match(/\?name=([^&]+)&/)[1];
document.writeln(matchobj); // prints 'reaojr'
Here's a single line answer that prevents having to store a variable (if you can't use URLSearchParams because you still support IE)
(document.location.search.match(/[?&]name=([^&]+)/)||[null,null])[1]
By adding in the ||[null,null] and surrounding it in parentheses, you can safely index item 1 in the array without having to check if match came back with results. Of course, you can replace the [null,null] with whatever you'd like as a default.
You can get the same result with simple .split() in javascript.
let value = url.split("name=")[1].split("&")[0];
This might work:
\??(.*=.+)*(&.*=.+)?
Related
I am making a calculator app and it basically builds a string that uses rhino to process an equation . But the problem is that I can't find a way to handle percentage . It does not accepts % symbol.
I need to replace all instances of it with "?/100*?" inside the string where the ?st is the number preceding the percentage and ?nd number used with percentage .
example "5 + 3% + 2" --> "5 + 5/100*3 + 2" .
The issue is I can't know what kind of number could be expected , it could even be something like (5+4)-(3+1)% or a long decimal. Since the percentage is inside a string I do not use variables .
Here is the example below (method that is invoked when equals button is pressed) :
btnEquals.setOnClickListener(v -> {
process = tvInput.getText().toString();
process = process.replaceAll("%", "?/100*?"); // this is the problem line
rhinoAndroidHelper = new RhinoAndroidHelper(this);
context = rhinoAndroidHelper.enterContext();
context.setOptimizationLevel(-1);
String finalResult = "";
try {
Scriptable scriptable = context.initStandardObjects();
finalResult = context.evaluateString(scriptable, process, "javascript", 1, null).toString();
} catch (Exception e) {
finalResult = "0";
}
tvOutput.setText(finalResult);
tvInput.setText("");
});
I am using this helper library : https://github.com/F43nd1r/rhino-android
I do not have experience in working with rhino so I do not know if there is a simple solution . I think that the only solution would be to build a complex string parsing method that will check what precedes the percentage and to reformat it . Is there any other way regarding rhino ?
Here is a string formatting method I wrote . It can properly handle any equation that contains a single % :
private void format(String s){
int newIndex = s.indexOf("%");
int nextIndex = newIndex;
StringBuilder percentage = new StringBuilder();
StringBuilder value = new StringBuilder();
char character;
String result = "";
StringBuilder newProcess = new StringBuilder(s);
boolean done = true;
boolean firstPartDone = false;
boolean firstSymbol = false;
while(done){
while (!firstPartDone){
if(nextIndex == 0){
done = false;
}
nextIndex--;
character = s.charAt(nextIndex);
if(character == '+' | character == '/' | character == '*' | character == '-'){
firstPartDone = true;
}else{
percentage.insert(0, character);
}
}
if(nextIndex == 0){
done = false;
}
character = s.charAt(nextIndex);
if(character == '+' | character == '/' | character == '*' | character == '-'){
if(!firstSymbol){
// value.insert(0, character);
nextIndex--;
firstSymbol = true;
}else{
done = false;
}
}else{
value.insert(0, character);
nextIndex--;
}
}
// percentage.append("%");
System.out.println(percentage);
System.out.println(value);
result = value + "/100*" + percentage;
String percent = percentage.toString();
String percentToReplace = percent.concat("%");
String finalString = newProcess.toString();
finalString = finalString.replace(percentToReplace, result);
process = finalString;
}
The problem with the method above is that it is still missing support to detect and handle brackets like (5+4)-(4+2)% . Which I can write . But it makes errors when there are two % present .
For instance : 5+10%-4+50% will become 5+ 5/10010 - 4 + 4/10050 .
The above equation will end up producing bad results for some reason . What would be necessary is inclusion of brackets etc ..
I just hoped that there was an easier way .
Rhino is a javascript engine without DOM support. If vanilla javascript can do it, Rhino can do it.
Since the meaning of % is context dependent, I don't think there's any easy way to use Rhino (vanilla javascript) to solve it. You need to parse it or find a library that will parse it. You can use javascript libraries with Rhino https://groups.google.com/g/mozilla.dev.tech.js-engine.rhino/c/fS8KQelY0bs
FYI - Baleudung says Rhino is obsolete and Nashorn is faster.
Original response:
Try using process = process.replaceAll("%", "/100");
replaceAll accepts a regex and every time the regex is found it replaces it with exactly the replacement value. In your first example it will be changed it to 5+3?/100*?+2, which is not valid javascript
/ has priority over + so it will adjust the values to percentages before adding the numbers.
Depending on how you want the calculator to work, this may have issues when multiple % are used. For example, 5+3%% or (1-3)+(1+2%)%. You need to decide if you want 3%% to mean 3/100/100 or not. If you want to reject %%, you could handle this in the input stage, by not letting %% be entered or after the input stage by parsing it to turn %% into %.
I need to write a regular expression that would match a string of value "*.log"
I have the following code and its doesnt seem to work as expected.
if (name.matches("\\*\\.log")
The above statement returns false, when the value of name is "*.log"
Any help is much appreciated.
Why are you doing that? Couldn't you just do
if(name.endsWith(".log"))
It seems to me like that would be a simpler option, since anything can be before .log, just like if you used a wildcard.
Also, if you want to make sure that it isn't just ".log", that is also very simple.
if(name.endsWith(".log") && !name.equals(".log"))
Hopefully I helped a bit!
I think this regular expression will helpful to you......
^\*\.log$
For php,
$re = "/\\*\\.log/";
$str = "*.log";
preg_match($re, $str, $matches);
For JavaScript,
var re = /\*\.log/;
var str = '*.log';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
For Python,
import re
p = re.compile(ur'\*\.log')
test_str = u"*.log"
re.search(p, test_str)
You can use this code :
String name="test.log";
if (name.matches("^.+\\.log$") ) {
System.out.println("Okay");
}
As simple as:
\*\.log
You can always check here:
https://www.regex101.com/r/vK7mQ6/2
What i'm trying to do is incorporate interface methods to complete a task given the variables inside of a string. The string i'm given, "s" can be made up numbers, +, -, and * symbols. The integer return is fairly easy as all i'm doing is returning an integer interface method of that int. However, for the other 3 symbols, I need to recursively incorporate a method to find the left and right nodes. I've posted my code below...
public static Expression parseString( String s ) {
String[] parse = s.split("\\s+");
String[] parsecopy;
Expression exp1;
Expression exp2;
if(s == null) {
return null;
}
if(parse[0].equals("+")) {
exp1 = parseString(parse[0]);
parsecopy = Arrays.copyOfRange(parse, 2, parse.length);
exp2 = parseString(parsecopy);
return new AddExpression(exp1, exp2);
}
else if() {
The problem - So my code creates a copy of the original string to find the next item in that string. I do this by using the Array function, copyOfRange(). However, when I want to call exp2 = parseString(parsecopy), i'm receiving an error because parseString takes in a string argument which has to be of the type String[]. The reason i'm trying to get parsecopy instead of parsecopy[0] is because parsecopy wouldn't create an endless loop and I would actually be able to iterate through the string.
Error code - The method parseString(String) in the type Parse is not applicable for the arguments (String[])
if(parse[0].equals("+")) {
exp1 = parseString(parse[0]);
parsecopy = Arrays.copyOfRange(parse, 2, parse.length);
exp2 = parseString(parsecopy);
return new AddExpression(exp1, exp2);
}
exp1 = parseString(parse[0]);
you are doing recursive calling here.
Since the parameter you pass to split is a regex, you can simply do:
String[] ss = "12121+34234 *23423 -123123 *123123-12312+1231231-123123".split("\\s?[\\+\\-\\*]\\s?");
this way you split your string wherever you got a +, - , or * (possibly with a whitespace after or before).
And please do the null-check of the string before split it :D
Hope it helps.
It seems like you want to check parse[1] equals "+" rather than parse[0].
You would expect 1 + 2 rather than + 1 2.
I have a program where the user will enter a string such as
PropertyA = "abc_*" and I need to have the asterisk match any character.
In my code, I'm grabbing the property value and replacing PropertyA with the actual value. For instance, it could be abc_123. I also pull out the equality symbol into a variable.
It should be able to cover this type of criteria
PropertyB = 'cba'
PropertyC != '*-this'
valueFromHeader is the lefthand side and value is the righthand side.
if (equality.equals("=")) {
result = valueFromHeader.matches(value);
} else if (equality.equals("!=")) {
result = !valueFromHeader.matches(value);
}
EDIT:
The existing code had this type of replacement for regular expressions
final String ESC = "\\$1";
final String NON_ALPHA = "([^A-Za-z0-9#])";
final String WILD = "*";
final String WILD_RE_TEMP = "#";
final String WILD_RE = ".*";
value = value.replace(WILD, WILD_RE_TEMP);
value = value.replaceAll(NON_ALPHA,ESC);
value = value.replace(WILD_RE_TEMP, WILD_RE);
It doesn't like the underscore here...
abcSite_123 != abcSite_123 (evaluates to true)
abcSite_123$1.matches("abcSite$1123")
It doesn't like the underscore...
Replace * with .*..
value=value.replace("*",".*");//replace * with .*
This won't work if your value contain +,? since they all have special meaning in regex.Escape them if their are any..
Best Solution i come up with so far, given a textblock it finds those methods that have paramters, but also the function with parameter key like this: "get: function(key)".
public class JavaScriptMethodFinder
{
static readonly string pattern = #"(?<=\s(?<Begin>[a-zA-Z_][a-zA-Z0-9_]*?)\(|\G)\s*((['""]).+?(?<!\\)\2|\{[^}]+\}|[^,;'""(){}\)]+)\s*(?:,|(?<IsEnd>\)))";
private static readonly Regex RegEx = new Regex(pattern, RegexOptions.Compiled);
public IEnumerable<dynamic> Find(string text)
{
var t = RegEx.Matches(text);
dynamic current = null;
bool isBegin;
foreach (Match item in t)
{
if (isBegin = (item.Groups["Begin"].Value != string.Empty))
{
current = new ExpandoObject();
current.MethodName = item.Groups["Begin"].Value;
current.Parameters = new List<string>();
current.Parameters.Add(item.Groups[1].Value);
}else
current.Parameters.Add(item.Groups[1].Value);
if (item.Groups["IsEnd"].Value != string.Empty)
{
isBegin = false;
if(!(item.Groups["Begin"].Value != string.Empty))
current.Parameters.Add(item.Groups[1].Value);
yield return current;
}
}
}
}
I wanna find Methods and its Variables. Given two examples.
First Example
function loadMarkers(markers)
{
markers.push(
new Marker(
"Hdsf",
40.261330438503,
10.4877055287361,
"some text"
)
);
}
Second Example
var block = new AnotherMethod('literal', 'literal', {"key":0,"key":14962,"key":false,"key":2});
So far i have, tested here: http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
(?<=Marker\(|\G)\s*((?<name>['""]).+?(?<!\\)\2|\{[^}]+\}|[^,;'""(){}\)]+)\s*(?:,|\))
Found 5 matches:
"Hdsf", has 2 groups:
"Hdsf"
"
40.261330438503, has 2 groups:
40.261330438503
10.4877055287361, has 2 groups:
10.4877055287361
"some text" ) has 2 groups:
"some text"
"
) has 2 groups:
(?<=AnotherMethod\(|\G)\s*((?<name>['""]).+?(?<!\\)\2|\{[^}]+\}|[^,;'""(){}\)]+)\s*(?:,|\))
Found 3 matches:
'literal', has 2 groups:
'literal'
' (name)
'literal', has 2 groups:
'literal'
' (name)
{"key":0,"key":14962,"key":false,"key":2}) has 2 groups:
{"key":0,"key":14962,"key":false,"key":2}
(name)
I would like to combine it such that i have one expression
Match<(methodname)>
Group : parameter
Group : parameter
Group : parameter
Match<(methodname)>
Group : parameter
Group : parameter
Group : parameter
so when i scan a page which contains both cases, i will get two matches witch
ect the first capture being the method name and then the following is the paramters.
I been trying to modify what i already have, but its to complex with the LookBehind stuff for I to understand it.
Regex's are a very problematic approach for this type of project. Have you looked at using a genuine JavaScript parser/compiler like Rhino? That will give you full awareness of JavaScript syntax "for free" and the ability to walk your source code meaningfully.