Asked  7 Months ago    Answers:  5   Viewed   41 times

Suppose this string:

The   fox jumped   over    the log.

Turning into:

The fox jumped over the log.

What is the simplest (1-2 lines) to achieve this, without splitting and going into lists?

 Answers

98
>>> import re
>>> re.sub(' +', ' ', 'The     quick brown    fox')
'The quick brown fox'
Tuesday, June 1, 2021
 
daniel__
answered 7 Months ago
91

See this regex:

/^(?=.*Tim)(?=.*stupid).+/

Regex explanation:

  • ^ Asserts position at start of string.
  • (?=.*Tim) Asserts that "Tim" is present in the string.
  • (?=.*stupid) Asserts that "stupid" is present in the string.
  • .+Now that our phrases are present, this string is valid. Go ahead and use .+ or - .++ to match the entire string.

To use lookaheads more exclusively, you can add another (?=.*<to_assert>) group. The entire regex can be simplified as /^(?=.*Tim).*stupid/.

See a regex demo!

>>> import re
>>> str ="""
... Tim is so stupid.
... stupid Tim!
... Tim foobar barfoo.
... Where is Tim?"""
>>> m = re.findall(r'^(?=.*Tim)(?=.*stupid).+$', str, re.MULTILINE)
>>> m
['Tim is so stupid.', 'stupid Tim!']
>>> m = re.findall(r'^(?=.*Tim).*stupid', str, re.MULTILINE)
>>> m
['Tim is so stupid.', 'stupid Tim!']

Read more:

  • Regex with exclusion chars and another regex
Thursday, June 3, 2021
 
tiny
answered 7 Months ago
75

Unfortunately there is no such construct in Java.

It this kind of comparison is frequent in your code, you can implement a small function that will perform the check for you:

public boolean oneOfEquals(int a, int b, int expected) {
    return (a == expected) || (b == expected);
}

Then you could use it like this:

if(oneOfEquals(a, b, 0)) {
    // ...
}

If you don't want to restrict yourselft to integers, you can make the above function generic:

public <T> boolean oneOfEquals(T a, T b, T expected) {
    return a.equals(expected) || b.equals(expected);
}

Note that in this case Java runtime will perform automatic boxing and unboxing for primitive types (like int), which is a performance loss.

Thursday, June 3, 2021
 
muaaz
answered 7 Months ago
63

You can do this by using backreferences in combination with re.sub:

import re
val1 = '[{&quot;vmdId&quot;:&quot;Text1&quot;,&quot;vmdVersion&quot;:&quot;text2&quot;,&quot;vmId&quot;:&quot;text3&quot;},{&quot;vmId&quot;:&quot;text4&quot;,&quot;vmVersion&quot;:&quot;text5&quot;,&quot;vmId&quot;:&quot;text6&quot;}]'

ansstring = re.sub(r'(?<=:&quot;)([^(]*)', r'newg<1>' , val1)

print ansstring

g<1> is the text which is in the first ().

EDIT

Maybe a better approach would be to decode the string, change the data and encode it again. This should allow you to easier access the values.

import sys

# python2 version
if sys.version_info[0] < 3:
    import HTMLParser
    html = HTMLParser.HTMLParser()
    html_escape_table = {
        "&": "&amp;",
        '"': "&quot;",
        "'": "&apos;",
        ">": "&gt;",
        "<": "&lt;",
        }

    def html_escape(text):
        """Produce entities within text."""
        return "".join(html_escape_table.get(c,c) for c in text)

    html.escape = html_escape
else:
    import html

import json

val1 = '[{&quot;vmdId&quot;:&quot;Text1&quot;,&quot;vmdVersion&quot;:&quot;text2&quot;,&quot;vmId&quot;:&quot;text3&quot;},{&quot;vmId&quot;:&quot;text4&quot;,&quot;vmVersion&quot;:&quot;text5&quot;,&quot;vmId&quot;:&quot;text6&quot;}]'
print(val1)

unescaped = html.unescape(val1)
json_data = json.loads(unescaped)
for d in json_data:
    d['vmId'] = 'new value'

new_unescaped = json.dumps(json_data)
new_val = html.escape(new_unescaped)
print(new_val)

I hope this helps.

Friday, August 27, 2021
 
Miguel
answered 4 Months ago
12

After a day of no proposed solutions, I started to think that Java Graphics cannot erase individual items back to a transparent color. But it turns out that the improved Graphics2D, together with BufferedImage and AlphaComposite, provide pretty much exactly the functionality I was looking for, allowing me to both draw shapes and erase shapes (back to full transparency) in various layers.

Now I do the following in start():

    screenBuffer = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB);
    screenBufferGraphics = screenBuffer.createGraphics();

    overlayBuffer = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB);
    overlayBufferGraphics = overlayBuffer.createGraphics();

I have to use new BufferedImage() instead of createImage() because I need to ask for alpha. (Even for screenBuffer, although it is the background -- go figure!) I use createGraphics() instead of getGraphics() just because my variable screenBufferGraphics is now a Graphics2D object instead of just a Graphics object. (Although casting back and forth works fine too.)

The code in paint() is barely different:

        g.drawImage(screenBuffer, 0, 0, null);
        g.drawImage(overlayBuffer, 0, 0, null);

And objects are rendered (or erased) like this:

// render to background
    screenBufferGraphics.setColor(Color.red);
    screenBufferGraphics.fillOval(80,80, 40,40);
// render to overlay
    overlayBufferGraphics.setComposite(AlphaComposite.SrcOver);
    overlayBufferGraphics.setColor(Color.green);
    overlayBufferGraphics.fillOval(90,70, 20,60);
// render invisibility onto overlay
    overlayBufferGraphics.setComposite(AlphaComposite.DstOut);
    overlayBufferGraphics.setColor(Color.blue);
    overlayBufferGraphics.fillOval(70,90, 30,20);
// and flush just this locally changed region
    repaint(60,60, 80,80);

The final Color.blue yields transparency, not blueness -- it can be any color that has no transparency.

As a final note, if you are rendering in a different thread from the AWT-EventQueue thread (which you probably are if you spend a lot of time rendering but also need to have a responsive interface), then you will want to synchronize the above code in paint() with your rendering routine; otherwise the display can wind up in a half-drawn state.

If you are rendering in more than one thread, you will need to synchronize the rendering routine anyway so that the Graphics2D state changes do not interfere with each other. (Or maybe each thread could have its own Graphics2D object drawing onto the same BufferedImage -- I didn't try that.)

It looks so simple, it's hard to believe how long it took to figure out how to do this!

Wednesday, October 20, 2021
 
aurelijusv
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share