开发者

Regex to parse a single line starting with "My Password: " to the end of the line

开发者 https://www.devze.com 2023-02-21 08:44 出处:网络
I want to parse a line starting with the words \"My Password: \". The problem is that the 2 words have space in between them and there is a space after the colon (My<space>Password:<space>

I want to parse a line starting with the words "My Password: ". The problem is that the 2 words have space in between them and there is a space after the colon (My<space>Password:<space>Text<end of line>).

I am not able to parse the 2 words together with the colon to the end of the line. The regex expression is in Java. Any help will be highly appreciated.

EDIT:

I was trying the regex as String myRgex = "My Password:+(/S)*$"...

That was to make sure that I do not have any white spaces in the password and *$ was to make sure that I do it till the end of the line. Thanks for the quick replies. I am still struggling with it. Can anybody please help me with parsing it till the End of line ignoring any whitespaces and staring with the above mentioned words. Correct my regex if you've found it t开发者_如何学Goo be wrong.


Pattern regex = Pattern.compile("^My Password: (\\S*)$");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group(1);
}

should do it.

^              # Anchor the search at the start of the string
My Password:   # Literal "My Password: "
(\\S*)         # Any number of non-space characters
$              # Anchor the search at the end of string

Your regex had a few errors: Non-space-characters are abbreviated as \S, not /S. And in your regex, the * applies to the colon: My Password:* means "My Password", followed by zero or more colons.


I am not sure if I understood, you want to check for a line that starts with "My Password: " and has a space between "My" and "Password" and another one after the colon?

If so try this: /^My Password: .*/
Because the space character and the colon character are not reserved chars like the dot or star (*) you can just use them.

If you are looking for case insensitive (i.e. my pasSworD), put use it with the case flag at the end: /^my password: .*/i.

. is any single character
* means zero or more times

Edit:
You can put brackets between .* if you need to get the matches and are not only interested in the boolean evaluation of the regex: /^My Password: (.*)/.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号