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
Related
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:
\??(.*=.+)*(&.*=.+)?
i have the following in my code.
String viit = "android.permission.READ_SOCIAL_STREAM";
and
String biit = "READ";
How do i search if viit contains biit?
Please note that viit is not a sentence but more like a word.
Simple: you use one of the many methods on String, such as contains().
if (viit.contains(biit)) {
which will give true for an "exact" match. If you need something "more fuzzy", you would be turning to matches() fore example which takes a regular expression. Those allow for a great deal of "fine tuned" patterns to be used.
Use contains method.
String viit = "android.permission.READ_SOCIAL_STREAM";
String biit = "READ";
if(viit.contains(biit)) {
//int index = viit.indexOf(biit);
}
https://developer.android.com/reference/java/lang/String.html
You can try to find the string like below
if( string.indexOf("READ") >= 0 ) {
Log.i("available", "true");
}else {
Log.i("not available", "false");
}
you can also use String indexOf method. the contains method uses indexof underneath.
regards
Use the java String.indexOf() method.
In your example, this would be something like that:
boolean hit = viit.indexOf(biit) == -1 ? true : false;
You can omit the boolean if you don't need it, if indexOf has no hit it will return -1.
Or use the String.contains() method which gives a boolean straight away.
I have an url in this format:
http://www.example.com/path?param1=value1¶m2=value2
I need a regex to match the path and params1 and params2 in any order but if param3 is present then I need it to fail so:
String str1 = "/path?param1=value1¶m2=value2"; // This will match
String str2 = "/path?param2=value2¶m1=value1"; // This will match
String str3 = "/path?param1=value1¶m2=value¶m3=value3"; // This will not match
So for I've tried using lookarounds to match the parameters but it is failing:
/path\?(?!param3)(?=param1=.*)(?=param2=.*)
Any thoughts?
P.D. For the curious I'm trying to match a specific URL from an AndroidManifest.xml file https://developer.android.com/guide/topics/manifest/data-element.html
Try this one out:
^(?!.*param3)(?=.*param1=)(?=.*param2=).*$
https://regex101.com/r/rI1lH5/1
If you want the path in as well, then
^\/path(?!.*param3)(?=.*param1=)(?=.*param2=).*$
This started as a comment and I got a little carried away. You can sanitize the query and see if it matches the parameters you need it to and avoid regex all together (if possible)
private boolean checkProperQueryString(String url, String[] requiredKeys){
try{
UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(url);
// Check that you have the right number of parameters
List<UrlQuerySanitizer.ParameterValuePair> parameters =
sanitizer.getParameterList();
if(parameters == null || parameters.size() != requiredKeys.length)
return false;
// Check to make sure that the parameters you have are the
// correct ones
for(String key : requiredKeys){
if(TextUtils.isEmpty(sanitizer(getValue(key))
return false;
}
// We pass every test, success!
return true;
} catch(Exception e){
// Catch any errors (haven't tested this so not sure of errors)
e.printStackTrace();
return false;
}
}
You can then make the call doing something like this
boolean validUrl = checkProperQueryString(url, new String[]{"param1", "param2"});
This doesn't directly answer your question, again just too much for a comment :P
Let me know if this just adds confusion for anyone and I can remove it.
The regex provided by Michael works well but there is a glitch. It also evaluates newParam. So we should change that with:
^(?!.*(\\?|&)param3)(?=.*(\\?|&)param1=)(?=.*(\\?|&)param2=).*$
Basically we check if the parameter name starts with a ? or &. Also if you want to make a parameter optional then you can just put a ? at the end like:
(?!.*(\\?|&)param3)(?=.*(\\?|&)param1=)(?=.*(\\?|&)param2=)?.*$
In the above param2 is optional.
I am trying to assign a default value to variable if the variable holds an empty string. I used the following codes but they are not working out:
if (d.lat.trim().isEmpty())
latt = 9.0819990;
else {
latt = Double.valueOf(d.lat.trim()).doubleValue();
}
The above code results in an error:
cannot find symbol
symbol : method isEmpty()
location: class java.lang.String
then I used
if (" ".equals(d.lat.trim()))
latt = 9.0819990;
else {
latt = Double.valueOf(d.lat.trim()).doubleValue();
}
The code above jumps the if section and tries to convert the empty String into double thereby throwing error about empty string.
SO, what am I doing wrong?
The empty string is "", not " " (note that there is no space between the quotes).
NPE is correct.
But may I recommend Apache StringUtils .
http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String)
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
The first block looks ok to me, but you are probably compiling with Java5, which does not have the String.isEmpty() method yet.
What if you use String.length() == 0 instead of String.isEmpty() ?
Apache StringUtils is a very good way to solve the problems for the validation you're implementing. Nevertheless, it seems very strange the error that you can't use the .isEmpty method, what version of the JDK are you using? Try to change the version of your JDK in the classpath with a latest version (JDK 7) or at least with the JDK 6.
Also remember that empty String is represented by "", just the quotes without any blank. It seems the way you're validating is ok. You can try with something like this.
if (d.lat.trim().isEmpty() || d.lat.length == 0)
latt = 9.0819990;
else {
latt = Double.valueOf(d.lat.trim()).doubleValue();
// or as mentioned before: latt = Double.parseDouble(d.lat.trim());
}
I want to remove any tags such as
<p>hello <namespace:tag : a>hello</namespace:tag></p>
to become
<p> hello hello </p>
What is the best way to do this if it is regex for some reason this is now working can anyone help?
(<|</)[:]{1,2}[^</>]>
edit:
added
Definitely use an XML parser. Regex should not be used to parse *ML
You should not use regex for these purposes use a parser like lxml or BeautifulSoup
>>> import lxml.html as lxht
>>> myString = '<p>hello <namespace:tag : a>hello</namespace:tag></p>'
>>> lxht.fromstring(myString).text_content()
'hello hello'
Here is a reason why you should not parse html/xml with regex.
If you're just trying to pull the plain text out of some simple XML, the best (fastest, smallest memory footprint) would be to just run a for loop over the data:
PSEUDOCODE BELOW
bool inMarkup = false;
string text = "";
for each character in data // (dunno what you're reading from)
{
char c = current;
if( c == '<' ) inMarkup = true;
else if( c == '>') inMarkup = false;
else if( !inMarkup ) text += c;
}
Note: This will break if you encounter things like CDATA, JavaScript, or CSS in your parsing.
So, to sum up... if it's simple, do something like above and not a regular expression. If it isn't that simple, listen to the other guys an use an advanced parser.
This is a solution I personally used for a likewise problem in java. The library used for this is Jsoup : http://jsoup.org/.
In my particular case I had to unwrap tags that had an attribute with a particular value in them. You see that reflected in this code, it's not the exact solution to this problem but could put you on your way.
public static String unWrapTag(String html, String tagName, String attribute, String matchRegEx) {
Validate.notNull(html, "html must be non null");
Validate.isTrue(StringUtils.isNotBlank(tagName), "tagName must be non blank");
if (StringUtils.isNotBlank(attribute)) {
Validate.notNull(matchRegEx, "matchRegEx must be non null when an attribute is provided");
}
Document doc = Jsoup.parse(html);
OutputSettings outputSettings = doc.outputSettings();
outputSettings.prettyPrint(false);
Elements elements = doc.getElementsByTag(tagName);
for (Element element : elements) {
if(StringUtils.isBlank(attribute)){
element.unwrap();
}else{
String attr = element.attr(attribute);
if(!StringUtils.isBlank(attr)){
String newData = attr.replaceAll(matchRegEx, "");
if(StringUtils.isBlank(newData)){
element.unwrap();
}
}
}
}
return doc.html();
}