Affichage des articles dont le libellé est Active questions tagged regex - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged regex - Stack Overflow. Afficher tous les articles

dimanche 28 juin 2015

How do I search/replace all 'n(' -> 'n*(' and ')n' -> ')*n' within same equation?

Scenario:
The user can enter any number of parentheses pairs into an equation in String format. However I need to check to be sure that all parentheses '(' or ')' have an adjacent multiplier symbol ''. Hence '3(' should be '3(' as ')3' should be ')3'.

I need to replace all occurrences of possible 'n(' with 'n(' and ')n' with ')*n'.

Example: 1+5(3+4)7/2 ---> 1+5*(3+4)7/2

What is the correct regex what to do this?

I was thinking of something like '[0-9](' & )[0-9]'. But I don't know the full syntax of search for all assurances of patterns to be replaced with '' insert.

Making a [code][/code] for BBcode with php regex

I would like to make a [code][/code] tag for bbcode so that what would be inside wouldn't be taken into account by the php regex that I made.

Example :

Hello [b]newbie[/b], to write in bold, use the following : [code][b](YOURTEXT)[/b][/code]

Should return in HTML :

Hello <strong>newbie</strong>, to write in bold, use the following : [b](YOURTEXT)[/b]

Here is a view of a part of my bbcode function :

<?
function bbcode($var) {
   $var = preg_replace('`\[b\](.+)\[/b\]`isU', '<strong>$1</strong>', $var); 
   $var = preg_replace('`\[i\](.+)\[/i\]`isU', '<em>$1</em>', $var);
   $var = preg_replace('`\[u\](.+)\[/u\]`isU', '<u>$1</u>', $var);
   return $var;
}
?>

Thank you in advance for your kind help !


EDIT : Here is how I finally made it work :

<? 
function bbcode($var) {
$var2 = preg_split('`(\[code].*?\[/code])`isU', $var, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

$var = preg_replace('`\[b\](.+)\[/b\]`isU', '<strong>$1</strong>', $var); 
$var = preg_replace('`\[i\](.+)\[/i\]`isU', '<em>$1</em>', $var);
$var = preg_replace('`\[u\](.+)\[/u\]`isU', '<u>$1</u>', $var);

$var = preg_replace('`(\[code].*?\[/code])`isU', $var2[1], $var);
$var = preg_replace('`\[code\](.+)\[/code\]`isU', '<div>$1</div>', $var);
return $var;
}

$text = 'Hello [b]newbie[/b], to write in bold, use the following [u]lol[/u] : [code][b](YOURTEXT) [u]lol[/u][/b][/code] [b][u]LOL[/u][/b]';

echo bbcode($text); 
?>

HOWEVER, there is a new problem left : if the character chain starts directly with '[code]' for example

[code][b]hello[/b][/code] test

than the result will be :

test test

This is because $var2[1] now leads to what comes after the [/code].

Could someone please help me to make a better delimitation that would also work for that second character chain ? Thank you in advance !

Regex - parsing string into groups

I have specific log messages and I would like to parse it into groups. I would like to make an alternative version in case if my string is more specific.

My logs:

18:48:24:284 => [DEBUG] [xxx.yyy.zzz] [8] Message1
18:48:24:671 => [INFO] [uuu.www.aaa] [8] Method: 'ReturnType MethodName(MethodParameter)'. Line: ~30. Message2

I have written a regex:

(?<timestamp>\d+:\d+:\d+:\d+.*)\s+=>\s+\[(?<level>\w+)\]\s+\[(?<emmiter>.*)\]\s+\[(?<thread>\d+)\]\s+(?<message>.*)

which parses these messages into specific groups:

timestamp: 18:48:24:284
level: DEBUG
emmiter: xxx.yyy.zzz
thread: 8
message: Message1

timestamp: 18:48:24:671
level: INFO
emmiter: uuu.www.aaa
thread: 8
message: Method: 'ReturnType MethodName(MethodParameter)'. Line: ~30. Message2

But right now I would like to add 2 more groups, in case if they exist : method and Line

So, I would like to get results like this:

timestamp: 18:48:24:284
level: DEBUG
emmiter: xxx.yyy.zzz
thread: 8
method:
line: 
message: Message1

timestamp: 18:48:24:671
level: INFO
emmiter: uuu.www.aaa
thread: 8
method: ReturnType MethodName(MethodParameter)
line: ~30
message: Message2

Can you please help me with that? Everything I do results in parsing only Line1 or only Line2 properly, but I would like to parse them both with one regex.

finding repeated characters in a row (3 times or more) in a string

Here is the code for finding repeated character like A in AAbbbc

String stringToMatch = "abccdef";
    Pattern p = Pattern.compile("((\\w)\\2+)+");
    Matcher m = p.matcher(tweet);
    while (m.find())
    {
       System.out.println("Duplicate character " + m.group(0));
    }

Now the problem is that I want to find the characters that are repeated but 3 times or more in a row, when I change 2 to 3 in the above code it does not work, Can anyone help?

Trouble Understanding Regular Expression [duplicate]

This question already has an answer here:

I am trying to learn the regular expression and I have learnt some easier notations but unable to understand what does the below expression means. Please shed some light on it.

Sample Data :

create table targets ( target varchar2(15) );

REM INSERTING into TARGETS
SET DEFINE OFF;
Insert into TARGETS (TARGET) values ('aaa');
Insert into TARGETS (TARGET) values ('a b c');
Insert into TARGETS (TARGET) values ('b  b  b  b');
Insert into TARGETS (TARGET) values ('  bbb xx  ');
Insert into TARGETS (TARGET) values ('wdef def w');
Insert into TARGETS (TARGET) values ('defxdefdef');
Insert into TARGETS (TARGET) values (null);


select target,
       regexp_replace(target,'(d)ef|.','\1') intermediate_string

from targets;

If possible please direct me to some good site for learning Regular expressions. Thanks!

python regex use capture group to define another groups length { }

I am parsing streaming hex data with python regex. I have the following packet structure that I am trying to extract from the stream of packets:

'\xaa\x01\xFF\x44'

  • \xaa - start of packet
  • \x01 - data length [value can vary from 00-FF]
  • \xFF - data
  • \x44 - end of packet

i want to use python regex to indicate how much of the data portion of the packet to match as such:

r = re.compile('\xaa(?P<length>[\x00-\xFF]{1})(.*){?P<length>}\x44')

this compiles without errors, but it doesnt work. I suspect it doesnt work because it the regex engine cannot convert the <length> named group hex value to an appropriate integer for use inside the regex {} expression. Is there a method by which this can be accomplished in python without resorting to disseminating the match groups?

Background: I have been using erlang for packet unpacking and I was looking for something similar in python

Php: How to ignore newline in Regex

I've already found a lot of stackoverflow questions about this topic. But I cannot find out the solution out of these questions for my problem.

I have the following html:

<p><a name="first-title"></a></p>
<h3>First Title</h3>
<h2><a href='#second'>Second Title</a></h2>
<h3>Third Title</h3>

I want to find out the <h3> prepended by </a></p>. In this case, the output should be:

<h3>First Title</h3>

So I implement the following regular expression;

preg_match_all('/(?<=<\/a><\/p>)<h3>(.+?)<\/h3>/s',$html,$data);

The above regular expression cannot output anything from the above html. But if I remove the newlines from the html, the above regular expression can correctly output my desire result.

I would not like to remove newlines from the html if possible. How should I develop regular expression to ignore the newlines from the source string?

Please, help me.

Python // Regex // Tags

I am trying to extract some text from between

</br></td>, <td class="first">TEXT_1a<br>TEXT_1b
                                </br></td>, <td class="first">TEXT_2a<br>TEXT_2b
                                </br></td>, <td class="first">TEXT_3a<br>TEXT_3b
                                </br></td>, <td class="first">TEXT_4a<br>TEXT_4b
                                </br></td>, <td class="first">TEXT_5a<br>TEXT_5b
                                </br></td>, <td class="first">TEXT_6a<br>TEXT_6b

I used BeautifulSoup (BS4) text = first_td.renderContents() trimmed_text = text.strip() print trimmed_text to extract the text. However, I only get the first text after <td tag. Nevertheless I would like to extract all the text in the tags, preferably sorted in columns (array). After I went with BS and it did not work I thought Regex is the way to go. One minor thing, I am an absolute regex amateur...

Any ideas how to get the text out there?

Thank you in advance

Shell remove string including newlines

I am currently working on a custom source patcher and I'm having troubles with replacing string by another, including newlines.

For instance, I want to remove this pattern :

\n/* @patch[...]*/

In order to get this... :

this.is = code ;
/* @patch beta
    blah blah
*/
if (!this.is) return 0 ;
/* @patch end */

... to this :

this.is = code ;
if (!this.is) return 0 ;

And not this :

this.is = code ;
<- newline
if (!this.is) return 0 ;
<- newline


Using a shell script, I'm using sed command in order to do what I want :

sed -e "s|\/\* @patch.*\*\/||g" $file > $file"_2"

This works pretty well, but the newlines are still there.


This way doesn't work as sed can't parse newlines :

sed -e "s|\n\/\* @patch.*\*\/||g" $file > $file"_2"

Neither this method work : How can I replace a newline (\n) using sed? , nor tr (second answer on the same thread).


Would you have any solution to this ? Even heavy ones, performance is not important here.

P.S. : I am working on a web application, and in this case JavaScript files. Under Mac OS X Yosemite, but no matter what system I'm using, it seems to be a common issue for all bash users.


I found out another solution using Node.js for those who have troubles with their Awk version :

node -e "console.log(process.argv[1].replace(/[\n\r]\/\* @patch([\s\S]*?)\*\//mg, ''))" "`cat $filepath`"

How do I make Wget name files as part of URL?

Short story:

I want Wget to name downloaded files as they match regex token ([^/]*)

wget -r --accept-regex="^.*/([^/]*)/$" $MYURL

Full story:

I use GNU Wget to recursively download one specific folder under particular WordPress website. I use regex to accept only posts and nothing else. Here is how I use it:

wget -r --accept-regex="^.*/([^/]*)/$" $MYURL

It works and Wget follows all the desired URLs. However, it saves files as .../last_directory/index.html, but I want these files to be saved as last_directory.html (.html part is optional).

Is there a way to do that with Wget alone? Or would you suggest how to do the same thing with sed or similar tools?

Replace text on every selected line in a textarea

I have a textarea in my HTML where users can type something. There is a button near the textarea that adds a ' - ' to the beginning of a selected line to make it like a list.

For example if I have the following text:

This is a line of text

And I selected it all and pressed the button it would appear like this:

- This is a line of text

However, this only works when selecting one line. If I was to select two lines, it will only format the one line. Here is my code:

Javascript with some jQuery:

var selection = $("#answer" + questionNumber).getSelection();
if (selection.text != '') {
    $("#answer" + questionNumber).replaceSelectedText('  - ' + selection.text);
    return;
}

The .getSelection() and .replaceSelectedText() methods come from this jQuery plugin.

I though maybe by identifying if there are '\n' in the selection then adding the list styling to it, perhaps using regex, though I'm not sure how to go about coding that.

Here is a JSFiddle of my issue.

Check whether the string a number

I am trying to check whether the string a number is. I have tried the following which works seperatly but not together.

if (i.matches("\\d{2} | [0-9]"))

I appreciate any help.

How to escape xml for use in perl multiline search and replace?

I want to use perl to replace a key-value pair in an xml file, but I am having problems escaping the xml from the regex parser. All this is supposed to run from a bash script. So I have two variables:

macDefault="<key>DefaultVolume</key>\
                <string>91630106-4A1F-4C58-81E9-D51877DE2EAB</string>"

winDefault="<key>DefaultVolume</key>\
                <string>EBD0A8B3-EE3D-427F-9A83-099C37A90556</string>"

And I want perl to replace the occurrence of the value $macDefault with the value of $winDefault in the file config.plist

Unfortunately

perl -0pe  's/'"$macDefault"'/'"$winDefault"'/' config.plist

does not work, as perl reports:

Having no space between pattern and following word is deprecated at -e line 1.
Bareword found where operator expected at -e line 1, near "s/<key>DefaultVolume</key>                <string>91630106-4A1F-4C58-81E9-D51877DE2EAB</string"
Having no space between pattern and following word is deprecated at -e line 1.
Bareword found where operator expected at -e line 1, near "<string>EBD0A8B3"
        (Missing operator before EBD0A8B3?)
Bareword found where operator expected at -e line 1, near "427F"
        (Missing operator before F?)
Bareword found where operator expected at -e line 1, near "9A83"
        (Missing operator before A83?)
Bareword found where operator expected at -e line 1, near "099C37A90556"
        (Missing operator before C37A90556?)
syntax error at -e line 1, near "s/<key>DefaultVolume</key>                <string>91630106-4A1F-4C58-81E9-D51877DE2EAB</string"
Illegal octal digit '9' at -e line 1, at end of line
Illegal octal digit '9' at -e line 1, at end of line
Execution of -e aborted due to compilation errors.

Thanks for any help!

php remove all attributes from a tag

Here is my code:

$content2= preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $content1);

This code removes all attributes from all tags in my website, but what I want is to only remove attributes from the form tag. This is what I have tried:

$content2 = preg_replace("/<form([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $content1); 

and

$content2 = preg_replace("/<(form[a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $content1); 

Pyhton/RegEx: Exclude StopWords

I have such list:

stopwords = ['a', 'and', 'is']

and such sentence:

sentence = 'A Mule is Eating and drinking'

Expected output:

reduced = ['mule', 'eating', 'drinking']

I have so far:

reduced = filter(None, re.match(r'\W+', sentence.lower()))

Now how would you filter out the stopwords?

Edit: Note the upper to lowercase conversion

replacing curly brackets and text in it with node

I have a string

var str="Hello my name is {john/www.john.com} and welcome to my {site/www.site.com}."

i have extracted curly brackets and made an anchor tag out of them like

<a href="www.john.com">john</a>

What i am trying to do is replace curly brackets and content in them with these nodes. Is it possible using regExp? I have studied regExp on MDN but still cant figure out the way.

How to grep just strings "ip" into a file?

Do you guys know some other way?
I am trying to find every way to find a string in some text. I want to find more ways using grep or sed. (bear in mind It's case sensitive)
  • Every word (strings) containing string "ip" and redirect the output result in /root/found;
 grep ip /usr/share/dict/words/ > /root/found
  • Just words (strings) initiating with "ip" and redirect the output result in /root/found;
 grep ^ip  /ust/share/dict/words > /root/found 
  • Just the word "ip" and redirect the output result in /root/found;
grep ^ip$ /ust/share/dict/words > /root/found

Nginx space on regex condition

I'm trying to block some user-agents on Nginx, and it's working great:

location /page {
  if ($http_user_agent ~* (badUserAgent1|badUserAgent2) ) {
   add_header 'Content-Type' 'text/plain';
   return 200 'Hello World';
  }
 }

But if I add a string with space, I get an error:

invalid condition "$http_user_agent"

Example:

location /page {
  if ($http_user_agent ~* (badUserAgent1|bad user agent 2) ) {
   add_header 'Content-Type' 'text/plain';
   return 200 'Hello World';
  }
 }

I tried to use apostrophes like this: ("badUserAgent1"|"bad user agent 2") without success.

Validate a datetime using: Y-m-d H:m:s in javascript

Pretty simple question, how do i validate a datetime, so the input is both the correct format, but also a valid date unlike 2015-02-30 ....

2015-06-28 16:06:35 //Valid

Regex matching multiple delimiters

I am trying to split on the following delimiters: full stop, semi-colon, *, +, ? and -

I tried the following but I am not making any progress, any help will be appreciated:

sentences = re.split("[.-;]*[\+]*[\?]*[\*]*", txt)

here is the sample text I've been trying this on:

- Text Editor: Now you can edit plain text files with airport tools
* Updated Dropbox support 
* Improved
stability
- New icon

Expected output after the split is a list of items:

TextEditor: Now you can edit plain text files with airport tools, Updated Dropbox support, Improved stability, New icon