我有一些内容包含这样的文件:
文件1:
AAA
BBB
CCC
123
file2的:
AAA
BBB
123
我想只在前3行是字母或" file1"时才回显文件名。在上面的样本中。 我将3行合并为一行并将其与我的正则表达式[A-Z]进行比较,但由于某种原因无法将其匹配
我的剧本:
file=file1
if [[ $(head -3 $file|tr -d '\n'|sed 's/\r//g') == [A-Z] ]]; then
echo "$file"
fi
我用bash -x运行它,这是输出
+ file=file1
++ head -3 file1
++ tr -d '\n'
++ sed 's/\r//g'
+ [[ ASMUTCEDD == [A-Z] ]]
+exit
答案 0 :(得分:1)
你错过了什么:
grep
检查输入是否仅匹配[A-Z]
个字符(或者确实是Bash的内置正则表达式匹配,正如@Barmar指出的那样)if
语句中使用管道,而不使用[[ ... ]]
像这样:
file=file1
if head -n 3 "$file" | tr -d '\n\r' | grep -qE '^[A-Z]+$'; then
echo "$file"
fi
答案 1 :(得分:1)
要进行正则表达式匹配,您必须使用import pygame as pg
GREEN = pg.Color(0, 200, 90)
BLUE = pg.Color(0, 90, 200)
class Tile(pg.sprite.Sprite):
def __init__(self, position):
super().__init__()
self.image = pg.Surface((50, 50))
self.color = GREEN
self.image.fill(self.color)
self.rect = self.image.get_rect(topleft=position)
def change_color(self, color):
self.color = color
self.image.fill(self.color)
def main():
screen = pg.display.set_mode((800, 600))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
# Create the tiles and add them to the all_sprites group.
for y in range(10):
for x in range(12):
all_sprites.add(Tile((x*51, y*51)))
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
# If a mouse button was pressed.
elif event.type == pg.MOUSEBUTTONDOWN:
# Iterate over the sprites in the group.
for sprite in all_sprites:
# Check if the sprite's rect collides with the mouse pos.
if sprite.rect.collidepoint(event.pos):
# Finally change the color.
sprite.change_color(BLUE)
all_sprites.update()
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
,而不是=~
。正则表达式应为==
。如果字符串中的任何地方有字母,则正则表达式匹配,而不仅仅是字符串是字母。
^[A-Z]*$
答案 2 :(得分:0)
您可以使用内置函数和character classes来解决此问题: -
int index = Integer.parseInt(delete);
Element root = xml_document.getRootElement();
root.getChildren().remove(index);