简体   繁体   English

如果然后在java中使用正则表达式条件

[英]if then condition using regex in java

I have a pattern which goes like this 我有一个这样的模式

String1 :"String2",

i have to validate this pattern. 我必须验证这种模式。 here if u see there are two cases, the somestring1 can contain special characters if it is given within double quotes. 在这里,如果你看到有两种情况,somestring1可以包含特殊字符,如果它在双引号内给出。

eg: "xxxx-xxx" :"yyyyyyyy",--------> is valid
but  xxxx-xxx  :"yyyyyyyy",--------> is not valid
    "xxxx-xxx  :"yyyyyyyy",--------> is not valid

So i need to create a regex which will check whether the double quotes is closed properly if it is present in String1. 所以我需要创建一个正则表达式,它将检查双引号是否在String1中存在时是否正确关闭。

Short answer: Regex doesn't work like that. 简短的回答:正则表达式不是这样的。

What you can do however, is to use two separate patterns to validate: 但是,您可以使用两个单独的模式来验证:

\"[^\"]+?\" :.*

To check the one that can contain special characters, and: 检查可以包含特殊字符的那个,以及:

[a-zA-Z]+? :.*

To check the one that can't 检查一个不能的

EDIT: 编辑:

Thinking some more about it, you could combine the two patterns above like so: 想一想更多关于它,你可以将上面的两种模式结合起来:

^(\"[^\"]+?\"|[a-zA-Z]+?) :.*$

Which will match something :"something" and "some-thing" :"something" but not "some-thing : "something" or some-thing : "something" . Assuming that the string only contains the given text. 哪个会匹配something :"something""some-thing" :"something"但不是"some-thing : "something"some-thing : "something" 。假设该字符串仅包含给定的文字。

如果我理解你的问题,这个简单的正则表达式应该有效

\"string1\" :\"string2\"

Maybe something like this? 也许是这样的?

(?<normalString>^[a-zA-Z]+$)|(?<specialString>^".*?"$)

This will capture only az characters and put them in the "normalString" group, or if there's an string within quotation marks, capture that and put it in the "specialString" group. 这将仅捕获az字符并将它们放在“normalString”组中,或者如果引号内有字符串,则捕获该字符并将其放在“specialString”组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM